0% found this document useful (0 votes)
4 views84 pages

Unit 3 - Data Visualization Using Python

Unit 3 covers data visualization using Python, focusing on libraries like Matplotlib and Seaborn to create various types of charts such as bar charts, pie charts, histograms, scatter plots, and box plots. It emphasizes the importance of data visualization in simplifying complex data, revealing patterns, and improving communication. The document also discusses real-world applications, challenges, and provides examples of how to implement visualizations using Python code.

Uploaded by

Aastha Shukla
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views84 pages

Unit 3 - Data Visualization Using Python

Unit 3 covers data visualization using Python, focusing on libraries like Matplotlib and Seaborn to create various types of charts such as bar charts, pie charts, histograms, scatter plots, and box plots. It emphasizes the importance of data visualization in simplifying complex data, revealing patterns, and improving communication. The document also discusses real-world applications, challenges, and provides examples of how to implement visualizations using Python code.

Uploaded by

Aastha Shukla
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Unit 3: Data Visualization using

Python
Topics to be covered

● Bar chart, Pie chart, histogram, scatterplot, BoxPlot using matplotlip & seaborn
● Interactive Data Visualization
Data Visualization

Data visualization is a field in data analysis that deals with visual representation of data. It graphically plots data
and is an effective way to communicate inferences from data. Data visualization uses charts, graphs and maps
to present information clearly and simply. It turns complex data into visuals that are easy to understand. With
large amounts of data in every industry, visualization helps spot patterns and trends quickly, leading to faster
and smarter decisions.

Using data visualization, we can get a visual summary of our data. With pictures, maps and graphs, the human mind
has an easier time processing and understanding any given data. Data visualization plays a significant role in the
representation of both small and large data sets, but it is especially useful when we have large data sets, in which
it is impossible to see all of our data, let alone process and understand it manually.

Python provides various libraries that come with different features for visualizing data. All these libraries come with
different features and can support various types of graphs.
● Matplotlib
● Seaborn
● Bokeh
● Plotly
Common Types of Data Visualization
There are various types of visualizations where each has a unique purpose in data representation. Here are the most
common types:

1. Charts and Graphs: They are used to visualize data, with charts comparing data points across categories or
showing trends over time and graphs analyzing relationships between variables to identify correlations, trends
and outliers. Examples: Bar Charts, Line Charts, Pie Charts, Scatter Plots, Histograms, Box Plots.
2. Maps: They are used to display geographical data which provides spatial context to trends and patterns.
Examples: Geographic Maps, Heat Maps
3. Dashboards: They combine multiple visualizations into a single interface which provides real-time
insights and interactive features for users to explore data.
Importance of Data Visualization
Data visualization is essential for understanding and communicating information effectively. Here are some key reasons
why it's important:
1. Simplifies Complex Data: It turns large and complicated data into visual formats like charts and graphs,
making the information easier to understand.
2. Reveals Patterns and Trends: It helps identify trends, relationships and patterns that are not easily seen in raw
data or tables.
3. Saves Time: Visuals allow quicker interpretation of data, helping users spot key information at a glance instead
of manually scanning through numbers.
4. Improves Communication: It makes it easier to explain data insights to others, especially those who may not
be familiar with the technical details.
5. Tells a Clear Story: Data visuals guide the audience through the information step-by-step, making it easier to
reach conclusions and make informed decisions.
Real-World Use Cases for Data Visualization
Data visualization is used across various industries to improve decision-making and drive results. Here are a few
examples:

1. Business Analytics: Used to monitor company performance, track KPIs and make data-driven decisions by
visualizing trends, sales and customer metrics.
2. Healthcare: Helps in analyzing patient records, tracking disease outbreaks and managing hospital operations
through easy-to-read charts and dashboards.
3. Sports: Used to visualize player statistics, team performance and match outcomes, helping coaches and
analysts improve strategies and training plans.
4. Retail and E-commerce: Enables tracking of sales, customer preferences and inventory levels, helping
businesses adjust stock and marketing efforts effectively.
Challenges in Data Visualization
1. Data Quality: Accuracy of visualizations depends on the quality of the data. If the data is inaccurate or
incomplete, the insights from the visualization will be misleading.
2. Over-Simplification: Simplifying data too much can lead to important details being lost like using a pie chart
that oversimplifies complex relationships between categories.
3. Choosing the Right Visualization: Using the wrong type of visualization can distort the message. For
example, a pie chart might not work well with many categories which leads to confusion.
4. Overload of Information: Too much information in a visualization can overwhelm viewers. It's important to
focus on key data points and avoid clutter.
Data Visualization using Matplotlib in Python
Matplotlib is a used Python library used for creating static, animated and interactive data visualizations. It is built on
the top of NumPy and it can easily handles large datasets for creating various types of plots such as line charts, bar
charts, scatter plots, etc.

Matplotlib is an easy-to-use, low-level data visualization library that is built on NumPy arrays. It consists of various
plots like scatter plot, line plot, histogram, etc. Matplotlib provides a lot of flexibility.
To install this type the below command in the terminal.
pip install matplotlib
Database Used (dataset)

Tips Database

Tips database is the record of the tip given by the customers in a restaurant for two and a half months in the early
1990s. It contains 6 columns such as total_bill, tip, gender, smoker, day, time, size.
You can download the tips database from here.
Example:
import pandas as pd
# reading the database
data = pd.read_csv("[Link]")
# printing the top 10 rows
display([Link](10))

Output:
Visualizing Data with Pyplot using Matplotlib
Pyplot is a module in Matplotlib that provides a simple interface for creating plots. It allows users to generate
charts like line graphs, bar charts and histograms with minimal code.
1. Line Chart
Line chart is one of the basic plots and can be created using plot() function. It is used to represent a relationship
between two data X and Y on a different axis.
Syntax:
[Link](x, y)
Parameter: x, y Coordinates for data points.
Example: This code plots a simple line chart with labeled axes and
a title using Matplotlib.
import [Link] as plt
x = [10, 20, 30, 40]
y = [20, 25, 35, 55]
[Link](x, y)
[Link]("Line Chart")
[Link]('Y-Axis')
[Link]('X-Axis')
[Link]()
For a dataset
Example:
import pandas as pd
import [Link] as plt

# reading the database


data = pd.read_csv("[Link]")

# Scatter plot with day against tip


[Link](data['tip'])
[Link](data['day'])

# Adding Title to the Plot


[Link]("Scatter Plot")

# Setting the X and Y labels


[Link]('Day')
[Link]('Tip')

[Link]()

Output:
Customizing Line Chart
Line charts can be customized using various properties:
1. Color: Change the color of the line
2. Linewidth: Adjust the width of the line
3. Marker: Change the style of plotted points
4. Markersize: Change the size of the markers
5. Linestyle: Define the style of the line like solid, dashed,
etc.

Example: This code creates a customized line chart with a green


dashed line, thicker width, large circular markers and labeled axes
and title.
import [Link] as plt
x = [10, 20, 30, 40]
y = [20, 25, 35, 55]
[Link](x, y, color='green', linewidth=3,
marker='o', markersize=15, linestyle='--')
[Link]("Customizing Line Chart")
[Link]('Y-Axis')
[Link]('X-Axis')
[Link]()

Output
2. Bar Chart

Bar chart displays categorical data using rectangular bars whose lengths are proportional to the values they
represent. It can be plotted vertically or horizontally to compare different categories.
Syntax:
[Link](x, height)
Parameter:
● x: Categories or positions on x-axis.
● height: Heights of the bars (y-axis values).

Example: This code creates a simple bar chart to show total bills for different days. X-axis represents the days and
Y-axis shows total bill amount.
import [Link] as plt
x = ['Thur', 'Fri', 'Sat', 'Sun']
y = [170, 120, 250, 190]
[Link](x, y)
[Link]("Bar Chart")
[Link]("Day")
[Link]("Total Bill")
[Link]()

Output
For a dataset
Example:
import pandas as pd
import [Link] as plt

# reading the database


data = pd.read_csv("[Link]")

# Bar chart with day against tip


[Link](data['day'], data['tip'])

[Link]("Bar Chart")

# Setting the X and Y labels


[Link]('Day')
[Link]('Tip')

# Adding the legends


[Link]()

Output:
Customizing Bar Chart
Bar charts can be made more informative and visually appealing by customizing:
● Color: Fill color of the bars
● Edgecolor: Color of the bar edges
● Linewidth: Thickness of the edges
● Width: Width of each bar

Example: This code creates a customized bar chart with green bars, blue edges, thicker border lines and labeled axes and
title.
import [Link] as plt

x = ['Thur', 'Fri', 'Sat', 'Sun']


y = [170, 120, 250, 190]

[Link](x, y, color='green', edgecolor='black', linewidth=2)

[Link]("Customizing Bar Chart")


[Link]("Day")
[Link]("Total Bill")
[Link]()

Output
5. Pie Chart
Pie chart is a circular chart used to show data as proportions or percentages. It is created using the pie(), where
each slice (wedge) represents a part of the whole.
Syntax:
[Link](x, labels=None, autopct=None)
Parameter:
● x: Data values for pie slices.
● labels: Names for each slice.
● autopct: Format to display percentage (e.g., '%1.1f%%').

Example: This code creates a simple pie chart to visualize distribution of different car brands. Each slice of pie
represents the proportion of cars for each brand in the dataset.
import [Link] as plt
import pandas as pd
cars = ['AUDI', 'BMW', 'FORD','TESLA', 'JAGUAR',]
data = [23, 10, 35, 15, 12]
[Link](data, labels=cars)
[Link](" Pie Chart")
[Link]()
Customizing Pie Chart
To make pie charts more effective and visually appealing use:
● Explode: Moving the wedges of the plot
● Autopct: Label the wedge with their numerical value.
● Color: Colors of the slices
● Sadow: Used to create a shadow effect

Example: This code creates a customized pie chart with colored slices, exploded segments for emphasis, percentage
labels with two decimal places and a shadow effect for better visual appeal.
import [Link] as plt
import pandas as pd

cars = ['AUDI', 'BMW', 'FORD','TESLA', 'JAGUAR',]


data = [23, 13, 35, 15, 12]
explode = [0.1, 0.5, 0, 0, 0]
colors = ( "orange", "cyan", "yellow","grey", "green",)

[Link](data, labels=cars, explode=explode, autopct='%1.2f%%',colors=colors, shadow=True)


[Link]()

Output
3. Histogram
Histogram shows the distribution of data by grouping values into
bins. The hist() function is used to create it, with X-axis showing bins
and Y-axis showing frequencies.
Syntax:
[Link](x, bins=None)
Parameter:
● x: Input data.
● bins: Number of bins (intervals) to group data.

Example: This code plots a histogram to show frequency distribution of


total bill values from the list x. It uses 10 bins and adds axis labels and a
title for clarity.
import [Link] as plt
x = [7, 8, 9, 10, 10, 12, 12, 12, 13, 14, 14, 15, 16,
16, 17, 18, 18, 19, 20, 20, 21, 22, 23, 24, 25, 25,
26, 28, 30, 32, 35, 36, 38, 40, 42, 44, 48, 50]
[Link](x, bins=10, color='steelblue')
[Link]("Histogram")
[Link]("Total Bill")
[Link]("Frequency")
[Link]()

Output
For a dataset
Example:
import pandas as pd
import [Link] as plt

# reading the database


data = pd.read_csv("[Link]")

# histogram of total_bills
[Link](data['total_bill'])

[Link]("Histogram")

# Adding the legends


[Link]()

Output:
Customizing Histogram Plot
To make histogram plots more effective various customizations can be
applied:
● Bins: Number of groups (bins) to divide data into
● Color: Bar fill color
● Edgecolor: Bar edge color
● Linestyle: Style of the edges like solid, dashed, etc.
● Alpha: Transparency level (0 = transparent, 1 = opaque)

Example: This code creates a customized histogram with green bars, blue
edges, dashed border lines, semi-transparent fill and labeled axes and title.
import [Link] as plt
x = [7, 8, 9, 10, 10, 12, 12, 12, 13, 14, 14, 15, 16,
16, 17, 18, 18, 19, 20, 20, 21, 22, 23, 24, 25, 25, 26,
28, 30, 32, 35, 36, 38, 40, 42, 44, 48, 50]
[Link](x, bins=10, color='green',
edgecolor='blue',linestyle='--', alpha=0.5)
[Link]("Customizing Histogram Plot" )
[Link]("Total Bill")
[Link]("Frequency")
[Link]()

Output
4. Scatter Plot
Scatter plots are used to observe relationships between variables. The scatter() method in the matplotlib library is
used to draw a scatter plot.
Syntax:
[Link](x, y)
Parameter: x, y Coordinates of the points.
Example: This code creates a scatter plot to visualize the relationship between days and total bill amounts using
scatter().
import [Link] as plt

x = ['Thur', 'Fri', 'Sat', 'Sun', 'Thur', 'Fri', 'Sat', 'Sun']


y = [170, 120, 250, 190, 160, 130, 240, 200]

[Link](x, y)
[Link]("Scatter Plot")
[Link]("Day")
[Link]("Total Bill")
[Link]()

Output
Example:
import pandas as pd
import [Link] as plt

# reading the database


data = pd.read_csv("[Link]")
# Scatter plot with day against tip
[Link](data['day'], data['tip'])
# Adding Title to the Plot
[Link]("Scatter Plot")
# Setting the X and Y labels
[Link]('Day')
[Link]('Tip')
[Link]()

Output:

This graph can be more meaningful if we can add colors and also change the size of the points. We can do this by using the c and s
parameter respectively of the scatter function. We can also show the color bar using the colorbar() method.
Example:
import pandas as pd
import [Link] as plt

# reading the database


data = pd.read_csv("[Link]")

# Scatter plot with day against tip


[Link](data['day'], data['tip'], c=data['size'],
s=data['total_bill'])

# Adding Title to the Plot


[Link]("Scatter Plot")

# Setting the X and Y labels


[Link]('Day')
[Link]('Tip')

[Link]()

[Link]()

Output:
Customizing Scatter Plot
Scatter plots can be enhanced with:
● S: Marker size (single value or array)
● C: Color of markers or sequence of colors
● Marker: Marker style like circle, diamond, etc.
● Linewidths: Width of marker borders
● Edgecolor: Color of marker borders
● Alpha: Blending value, between 0 (transparent) and 1 (opaque)

Example: This code creates a customized scatter plot using diamond-shaped


markers, where color represents size, marker size reflects the total bill and
transparency is added for better visualization. It includes labeled axes and a title.
import [Link] as plt
x = ['Thur' , 'Fri', 'Sat', 'Sun', 'Thur' , 'Fri', 'Sat',
'Sun']
y = [170, 120, 250, 190, 180, 130, 260, 200]
size = [2, 3, 4, 2, 3, 2, 4, 3]
bill = [170, 120, 250, 190, 180, 130, 260, 200]
[Link](x, y, c =size, s =bill, marker ='D', alpha =0.5)
[Link]( "Customizing Scatter Plot" )
[Link]( "Day")
[Link]( "Total Bill" )
[Link]()

Output
6. Box Plot
Box plot is a simple graph that shows how data is spread out. It displays the minimum, maximum, median and quartiles and
also helps to spot outliers easily.
Syntax:
[Link](x, notch=False, vert=True)
Parameter:
● x: Data for which box plot is to be drawn (usually a list or array).
● notch: If True, draws a notch to show the confidence interval around the median.
● vert: If True, boxes are vertical. If False, they are horizontal.

Example: This code creates a box plot to show the data distribution and compare three groups using matplotlib
import [Link] as plt

data = [ [10, 12, 14, 15, 18, 20, 22],


[8, 9, 11, 13, 17, 19, 21],
[14, 16, 18, 20, 23, 25, 27] ]

[Link](data)
[Link]("Groups")
[Link]("Values")
[Link]("Box Plot")
[Link]()

Output
Matplotlib’s Core Components: Figures and Axes
1. Figure class
The Figure class represents the full drawing area or canvas that can hold one or more plots. It is created using the figure() function and lets user
control the overall size, layout and background of the plot window.
Syntax: [Link](figsize=None, facecolor=None)
Parameter:
● figsize: Sets size of the figure (width, height) in inches.
● facecolor: Sets background color of the figure.
Example: This code demonstrates how to use Figure class to create a simple line plot. It sets figure size and background color, adds custom axes, plots data
and labels the axes and title.
import [Link] as plt
# Create a Figure with basic size and background color
fig = [Link](figsize=(6, 4), facecolor='lightblue')
# Add Axes to the Figure [left, bottom, width, height] :
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
x = [1, 2, 3, 4]
y = [10, 20, 15, 25]
[Link](x, y)
[Link]("Simple Line Plot")
[Link]("X-Axis")
[Link]("Y-Axis")
[Link]()

Output
Explanation:
● fig.add_axes() adds an Axes object to the figure.
● [0.1, 0.1, 0.8, 0.8] defines the position left, bottom, width and height as a fraction of figure size.
2. Axes Class
Axes class represents actual plotting area where data is drawn. It is the most basic and flexible for creating plots or subplots within a figure.
A single figure can contain multiple axes but each Axes object belongs to only one figure. It can create an Axes object using axes()
function.
Syntax:
axes([left, bottom, width, height])

Example: This code creates a figure using Figure class and adds a custom axes area to it. It then plots two line graphs one for x vs y and
another for y vs x. The graph includes axis labels, a title and a legend for better clarity and presentation.
import [Link] as plt
from [Link] import Figure
x = [10, 20, 30, 40]
y = [20, 25, 35, 55]
fig = [Link](figsize =(5, 4))
ax = fig.add_axes([ 0.1, 0.1, 0.8, 0.8])
[Link](x, y)
[Link](y, x)
ax.set_title( "Linear Graph" )
ax.set_xlabel( "X-Axis" )
ax.set_ylabel( "Y-Axis" )
[Link](labels =('line 1' , 'line 2' ))
[Link]()

Output
Data Visualization with Seaborn - Python

Seaborn is a popular Python library for creating attractive statistical visualizations. Built on Matplotlib and integrated
with Pandas, it simplifies complex plots like line charts, heatmaps and violin plots with minimal code.

Seaborn is a high-level interface built on top of the Matplotlib. It provides beautiful design styles and color palettes to
make more attractive graphs.

To install seaborn type the below command in the terminal.

pip install seaborn


Seaborn is built on the top of Matplotlib, therefore it can be used with the Matplotlib as well. Using both Matplotlib
and Seaborn together is a very simple process. We just have to invoke the Seaborn Plotting function as normal, and
then we can use Matplotlib’s customization function.

Note: Seaborn comes loaded with dataset such as tips, iris, etc. but for the sake of this tutorial we will use Pandas for
loading these datasets.
Example:
# importing packages

import seaborn as sns


import [Link] as plt
import pandas as pd

# reading the database


data = pd.read_csv("[Link]")

# draw lineplot
[Link](x="sex", y="total_bill", data=data)

# setting the title using Matplotlib


[Link]('Title using Matplotlib Function')

[Link]()

Output:
Creating Plots with Seaborn
Seaborn makes it easy to create clear and informative statistical plots with just a few lines of
code. It offers built-in themes, color palettes, and functions tailored for different types of
data.

1. Line plot
A line plot shows the relationship between two numeric variables, often over time. It can
also compare multiple groups using different lines.
Syntax: [Link](x=None, y=None, data=None)
Parameters:
● x, y: Numeric input variables. These can be arrays, lists or column names from a
DataFrame.
● data: DataFrame containing the data.

Example:
import pandas as pd
import [Link] as plt
data = {'Name': ['ANSH', 'SAHIL', 'JAYAN', 'ANURAG'], 'Age': [21, 23,
20, 24]}
df = [Link](data)
[Link]([Link], df['Age'])
[Link]('Index')
[Link]('Age')
[Link]('Age Line Plot')
[Link]()

Output
Example 2:
For Dataset
# importing packages
Example: import seaborn as sns
import [Link] as plt
# importing packages import pandas as pd
import seaborn as sns
import [Link] as plt
import pandas as pd # reading the database
data = pd.read_csv("[Link]")
# reading the database
data = pd.read_csv("[Link]") # using only data attribute
[Link](data=[Link](['total_bill']
[Link](x='day', y='tip', data=data) , axis=1))
[Link]() [Link]()

Output: Output:
2. Scatter Plot
Scatter plots are used to visualize the relationship between two numerical
variables. They help identify correlations or patterns. It can draw a
two-dimensional graph.
Syntax:
[Link](x=None, y=None, data=None)
Parameters:
● x, y: Input data variables that should be numeric.
● data (optional): Dataset containing the variables.

Returns: An Axes object with the scatter plot.


Example:
import pandas as pd
import seaborn as sns
import [Link] as plt
data = {'Name': ['ANSH', 'SAHIL', 'JAYAN', 'ANURAG'],
'Age': [21, 23, 20, 24]}
df = [Link](data)
[Link](x=[Link], y='Age', data=df)
[Link]()

Output
You will find that while using Matplotlib it will a lot difficult if you want
For Dataset to color each point of this plot according to the gender. But in scatter plot
it can be done with the help of hue argument.
Example:
Example:
# importing packages
import seaborn as sns # importing packages
import [Link] as plt import seaborn as sns
import pandas as pd import [Link] as plt
import pandas as pd
# reading the database
data = pd.read_csv("[Link]") # reading the database
data = pd.read_csv("[Link]")
[Link](x='day', y='tip', data=data,)
[Link]() [Link](x='day', y='tip', data=data,
hue='gender')
Output: [Link]()

Output:
3. Box plot
A box plot is the visual representation of the depicting groups of numerical data with their quartiles against
continuous/categorical data. It consists of 5 key statistics: Minimum ,First Quartile or 25% , Median (Second Quartile) or
50%, Third Quartile or 75% and Maximum
Syntax:
[Link](x=None, y=None, hue=None, data=None)
Parameters:
● x, y, hue: Variables for plotting long-form data.
● data: Dataset to plot. If x and y are absent data is treated as wide-form.
Returns: An Axes object with the box plot.
Example
import pandas as pd
import [Link] as plt
import seaborn as sns

data = {'Name': ['ANSH', 'SAHIL', 'JAYAN', 'ANURAG'], 'Age': [21, 23, 20, 45]}
df = [Link](data)

[Link](y='Age', data=df)
[Link]()

Output
4. Bar plot
Barplot represents an estimate of central tendency for a numeric variable with the height of each rectangle and
provides some indication of the uncertainty around that estimate using error bars.
Syntax:
[Link](x=None, y=None, hue=None, data=None)
Parameters :
● x, y : Variables or column names for long-form data.
● hue : (optional) Column for color encoding.
● data : (optional) Dataset to plot.
Returns: Axes object with the bar plot.
Example:
import pandas as pd
import seaborn as sns
import [Link] as plt

data = {'Name': ['ANSH', 'SAHIL', 'JAYAN', 'ANURAG'], 'Age': [21, 23, 20, 24]}
df = [Link](data)

[Link](x='Name', y='Age', data=df)


[Link]()

Output
For Dataset:

Example:
# importing packages
import seaborn as sns
import [Link] as plt
import pandas as pd

# reading the database


data = pd.read_csv("[Link]")

[Link](x='day',y='tip', data=data, hue='gender')

[Link]()

Output:
5. Histogram
The histogram in Seaborn can be plotted using the histplot() function.

Example:
# importing packages
import seaborn as sns
import [Link] as plt
import pandas as pd

# reading the database


data = pd.read_csv("[Link]")

[Link](x='total_bill', data=data, kde=True, hue='gender')

[Link]()

Output:
How to Customize Seaborn Plots with Python?
Customizing Seaborn plots increases their readability and visual appeal which makes the data insights clearer and more
informative. Here are several ways we can customize our plots in Seaborn:

1. Adding Titles and Axis Labels


Adding descriptive titles and axis labels makes our plots more understandable and informative. Using Matplotlib's
[Link](), [Link]() and [Link]() to set titles and axis labels.
import seaborn as sns
import [Link] as plt

iris = sns.load_dataset('iris')
[Link](x='sepal_length', y='sepal_width', data=iris)

# Add plot title and axis labels


[Link]('Sepal Length vs Sepal Width')
[Link]('Sepal Length (cm)')
[Link]('Sepal Width (cm)')
[Link]()

Output
2. Built-in Styles and Grids in Seaborn
Seaborn provides built-in styles that control the background and grid of your plots. These styles improve readability and can be chosen
based on your presentation needs.
Available Styles:
● darkgrid – Dark background with light gridlines. Great for clear contrast.
● whitegrid – White background with light gridlines. Ideal for statistical plots.
● dark – Dark background without gridlines. Clean and modern look.
● white – Plain white background without gridlines. Good for simple visuals.
● ticks – White background with axis ticks styled sharply. Suitable for publications.

import seaborn as sns


import [Link] as plt

sns.set_style("whitegrid")

[Link](x='species', y='petal_length',
data=sns.load_dataset('iris'))
[Link]('Petal Length Distribution by Species')
[Link]()

Output
3. Customizing Color Palettes
Seaborn makes it easy to enhance the appearance of plots using color palettes. You can choose from built-in palettes like
"deep", "muted", or "bright" or define your own using sns.color_palette(). Customizing colors improves clarity and helps
match your data’s theme or purpose.

a) Using a Built-in Palette:

import seaborn as sns


import [Link] as plt
# Set built-in palette
sns.set_palette("pastel")
# Load dataset
data = sns.load_dataset('iris')
# Create bar chart
[Link](x='species', y='petal_length',
data=data)
[Link]('Average Petal Length by Species')
[Link]()
b) Using a Custom Palette:

import seaborn as sns


import [Link] as plt

# Define custom colors


custom_colors = ['#FF5733', '#33FFBD', '#335BFF']

# Set custom palette


sns.set_palette(custom_colors)

# Load dataset
data = sns.load_dataset('iris')

# Create bar chart with hue


[Link](x='species', y='petal_length',
hue='species', data=data)

[Link]('Custom Colored Average Petal Length')


[Link]().remove() # optional: removes duplicate
legend
[Link]()
4. Adjusting Figure Size and Aspect Ratio
We can adjust the figure size using [Link](figsize=(width,height)) to control the plot's dimensions. This allows for
better customization to fit different presentation or reports.
[Link](figsize=(10, 6))

[Link](x='year', y='passengers', data=sns.load_dataset('flights'))


[Link]('Number of Passengers Over Time')
[Link]()

Output
5. Adding Markers to Line Plots
Markers can be added to Seaborn line plots using the marker argument to highlight data points. For example adding
circular markers to the line plot using [Link](x='x', y='y' ,marker='o')
[Link](x='year', y='passengers', data=sns.load_dataset('flights'), marker='o')
[Link]('Number of Passengers Over Time')
[Link]()

Output
Interactive data visualization
Interactive data visualization refers to the graphical representation of data that allows users to interact directly
with the visual elements. This includes features like hovering, clicking, filtering, zooming and drilling down to gain
deeper insights. It turns passive viewing into active exploration, helping users discover hidden trends, patterns and
correlations.
Examples of interactions include:
● Hovering to display tooltips
● Filtering data using dropdowns or sliders
● Clicking to drill into subcategories
● Dynamically adjusting time ranges

Importance of Interactive Data Visualization


Interactive visualizations go beyond traditional data representation. They:
● Allow users to explore multiple scenarios
● Simplify complex datasets
● Provide contextual understanding
● Facilitate real-time decision-making
Key Advantages:

1. Enhanced Data Understanding: Interactivity brings data to life, helping users understand relationships,
patterns, and anomalies.
2. Improved Exploration: Users can explore various subsets of the data, zoom into areas of interest, and
generate new questions from the visuals.
3. Effective Communication: Visuals act as a universal language. Dynamic dashboards help present insights to a
wide audience clearly and convincingly.
4. Faster and Better Decision-Making: Real-time updates and drill-down options help users identify KPIs,
outliers and trends instantly.
Features and Benefits of Modern Interactive Visualizations
Numerous elements that increase data analysis and user experience are available in modern interactive data visualizations:
● Filtering and Slicing: By allowing users to compare different segments, concentrate on certain data subsets, or examine data from
many dimensions, interactive filters and slicing tools may uncover hidden patterns.
● Updates in real time: By connecting visualizations to real-time data sources, users can keep an eye on changes and respond to
them as they happen.
● Customizable Views: Users may rearrange dashboard components for individualized insights, choose certain metrics, or change
the style of graphic to better suit their needs.
● Collaborative Features: A lot of modern technologies come with collaborative features that let teams debate findings, share and
annotate visualizations, and make choices based on data and tactics in tandem.
● Advanced Analytics: By combining statistical models, machine learning algorithms, and predictive analytics, one may better
detect patterns, correlations, and anomalies, which facilitates more precise forecasting and decision-making.
● Data Integration: With the help of modern platforms, disparate data sources may be integrated to provide a single picture of the
data and make it easier to conduct thorough analyses that take into account a variety of aspects.

Better data interpretation, a quicker time to insight, more teamwork, and more efficient communication are some advantages of these qualities,
which improve decision-making and business results.
The most popular libraries for interactive data visualization in Python are Plotly, Bokeh, and Altair.

● Plotly: Widely used for creating interactive, web-based plots and dashboards. It offers a large variety of
chart types, including 3D and geographic maps, and its plots feature built-in interactivity like zooming,
panning, and hover-over tooltips. It integrates well with Dash for building full-fledged interactive web
applications.
● Bokeh: Focuses on producing high-performance, web-ready visualizations for large or streaming
datasets. Based on the "Grammar of Graphics," it allows for highly customizable interactive features like
sliders and filters, which can be embedded in web pages or Jupyter notebooks.
● Altair: A declarative statistical visualization library that provides a simple and consistent API for
creating elegant interactive charts with minimal code. It is well-regarded for exploratory data analysis, as
its declarative nature allows users to focus on what to visualize rather than how to draw it.
Interactive Data Visualization with Bokeh

Python Bokeh is a Data Visualization library that provides interactive charts and plots. Bokeh renders its plots using
HTML and JavaScript that uses modern web browsers for presenting elegant, concise construction of novel
graphics with high-level interactivity.
Features of Bokeh:
● Flexibility: Bokeh can be used for common plotting requirements and for custom and complex use-cases.
● Productivity: Its interaction with other popular Pydata tools (such as Pandas and Jupyter notebook) is very
easy.
● Interactivity: It creates interactive plots that change with the user interaction.
● Powerful: Generation of visualizations for specialized use-cases can be done by adding JavaScript.
● Shareable: Visual data are shareable. They can also be rendered in Jupyter notebooks.
● Open source: Bokeh is an open-source project.

Bokeh is mainly famous for its interactive charts visualization. Bokeh renders its plots using HTML and JavaScript that
uses modern web browsers for presenting elegant, concise construction of novel graphics with high-level interactivity.
To install this type the below command in the terminal.
pip install bokeh
Basic Concepts of Bokeh
Bokeh is simple to use as it provides a simple interface to the data scientists who do not want to be distracted by its
implementation and also provides a detailed interface to developers and software engineers who may want more control
over the Bokeh to create more sophisticated features. To do this Bokeh follows the layered approach.

[Link]

This class is the Python Library for Bokeh that contains model classes that handle the JSON data created by Bokeh's
JavaScript library (BokehJS). Most of the models are very basic consisting of very few attributes or no methods.

[Link]

This is the mid-level interface that provides Matplotlib or MATLAB like features for plotting. It deals with the data
that is to be plotted and creating the valid axes, grids, and tools. The main class of this interface is the Figure class.
After the installation and learning about the basic concepts of Bokeh let's create a simple plot.

Example:
# importing the modules
from [Link] import figure, output_file, show

# instantiating the figure object


graph = figure(title = "Bokeh Line Graph")

# the points to be plotted


x = [1, 2, 3, 4, 5]
y = [5, 4, 3, 2, 1]

# plotting the line graph


[Link](x, y)

# displaying the model


show(graph)

Output:
Annotations and Legends
Annotations are the supplemental information such as titles, legends, arrows, etc that can be added to the graphs. In the above example, we have already
seen how to add the titles to the graph. In this section, we will see about the legends.
Adding legends to your figures can help to properly describe and define them. Hence, giving more clarity. Legends in Bokeh are simple to implement. They
can be basic, automatically grouped, manually mentioned, explicitly indexed, and also interactive.
Example:
# importing the modules
from [Link] import figure, output_file, show
# instantiating the figure object
graph = figure(title="Bokeh Line Graph")
# the points to be plotted
x = [1, 2, 3, 4, 5]
y = [5, 4, 3, 2, 1]
# plotting the 1st line graph
[Link](x, x, legend_label="Line 1")
# plotting the 2nd line graph with a
# different color
[Link](y, x, legend_label="Line 2",
line_color="green")
# displaying the model
show(graph)

Output:
In the above example, we have plotted two different lines with a legend that simply states that which is line 1 and which is line 2. The color in the legends is
also differentiated by the color.
Plotting Different Types of Plots
Glyphs in Bokeh terminology means the basic building blocks of the Bokeh plots such as lines, rectangles, squares, etc. Bokeh plots are
created using the [Link] interface which uses a default set of tools and styles.
Line Plot
Line charts are used to represent the relation between two data X and Y on a different axis. A line plot can be created using the line() method
of the plotting module.
Syntax:
line(parameters)
Example:
# importing the modules
from [Link] import figure, output_file, show

# instantiating the figure object


graph = figure(title = "Bokeh Line Graph" )

# the points to be plotted


x = [1, 2, 3, 4, 5]
y = [5, 4, 3, 2, 1]

# plotting the line graph


[Link](x, y)

# displaying the model


show(graph)

Output:
Example:
from [Link] import figure, output_file, show
import pandas as pd

# Output file
output_file("tips_chart.html")

# Read data
data = pd.read_csv("[Link]")

# Count values
df = data['tip'].value_counts()

# Create figure
graph = figure(title="Tip Frequency Line Chart",
x_axis_label='Tip Amount',
y_axis_label='Count')

# Plot (correct)
[Link](x=[Link], y=[Link])

# Show plot
show(graph)

Output:
Bar Plot
Bar plot or Bar chart is a graph that represents the category of data with rectangular bars with lengths and heights that is proportional to the
values which they represent. It can be of two types horizontal bars and vertical bars. Each can be created using the hbar() and vbar() functions
of the plotting interface respectively.
Syntax:
hbar(parameters)
vbar(parameters)
Example 1: Creating horizontal bars.
# importing the modules
from [Link] import figure, output_file, show
# instantiating the figure object
graph = figure(title = "Bokeh Bar Graph" )
# the points to be plotted
x = [1, 2, 3, 4, 5]
y = [1, 2, 3, 4, 5]
# height / thickness of the plot
height = 0.5
# plotting the bar graph
[Link](x, right = y, height = height)
# displaying the model
show(graph)

Output:
Example 2: Creating the vertical bars
# importing the modules
from [Link] import figure, output_file, show

# instantiating the figure object


graph = figure(title = "Bokeh Bar Graph")

# the points to be plotted


x = [1, 2, 3, 4, 5]
y = [1, 2, 3, 4, 5]

# height / thickness of the plot


width = 0.5

# plotting the bar graph


[Link](x, top = y, width = width)

# displaying the model


show(graph)

Output:
Example:
# importing the modules
from [Link] import figure, output_file, show
import pandas as pd

# instantiating the figure object


graph = figure(title = "Bokeh Bar Chart")

# reading the database


data = pd.read_csv("[Link]")

# plotting the graph


[Link](data['total_bill'], top=data['tip'], width=0.5)

# displaying the model


show(graph)

Output:
Scatter Plot
A scatter plot is a set of dotted points to represent individual pieces of data in the horizontal and vertical axis. A graph in which the values of two variables
are plotted along X-axis and Y-axis, the pattern of the resulting points reveals a correlation between them. It can be plotted using the scatter() method of the
plotting module.
Syntax:
scatter(parameters)

Example:
# importing the modules
from [Link] import figure, output_file, show
from [Link] import magma
import random

# instantiating the figure object


graph = figure(title = "Bokeh Scatter Graph")
# points to be plotted
x = [n for n in range(256)]
y = [[Link]() + 1 for n in range(256)]

# plotting the graph


[Link](x, y)
# displaying the model
show(graph)

Output:
Example:
# importing the modules
from [Link] import figure, output_file, show
from [Link] import magma
import pandas as pd

# instantiating the figure object


graph = figure(title = "Bokeh Scatter Graph")

# reading the database


data = pd.read_csv("[Link]")

color = magma(256)

# plotting the graph


[Link](data['total_bill'], data['tip'], color=color)

# displaying the model


show(graph)

Output:
Pie Chart
Bokeh does not provide a direct method to plot the Pie Chart. It can be created using the wedge() method. In the wedge() function, the primary parameters are the x
and y coordinates of the wedge, the radius, the start_angle and the end_angle of the wedge. In order to plot the wedges in such a way that they look like a pie chart, the
x, y, and radius parameters of all the wedges will be the same. We will only adjust the start_angle and the end_angle.

Syntax:
wedge(parameters)

Example:
# importing the modules
from [Link] import figure, output_file, show
# instantiating the figure object
graph = figure(title = "Bokeh Wedge Graph")
# the points to be plotted
x = 0
y = 0
# radius of the wedge
radius = 15
# start angle of the wedge
start_angle = 1
# end angle of the wedge
end_angle = 2
# plotting the graph
[Link](x, y, radius = radius,
start_angle = start_angle,
end_angle = end_angle)
# displaying the model
show(graph)

Output:
Creating Different Shapes
The Figure class in Bokeh allows us create vectorised
glyphs of different shapes such as circle, rectangle, oval,
polygon, etc.
1. Circle 4. Rectangle
● Methods:
● Method: rect()
○ circle() → simple circle
○ circle_cross() → circle with “+” inside
● Used to draw rectangles
○ circle_x() → circle with “X” inside ● Requires: x, y, width, and height
● Requires: x and y coordinates of center

2. Oval 5. Polygon
● Method: oval() ● Method: multi_polygons()
● Used to draw oval shapes ● Used to draw multiple polygons
● Requires: x, y, width, and height ● Requires: list of x-coordinates and
y-coordinates
3. Triangle
● Method: triangle()
● Used to plot triangle glyphs
● Requires: x and y coordinates + size
Example
from [Link] import figure, show
# Create a figure
p = figure(title="Bokeh Shapes Example")
# Circle
[Link](x=[1, 2], y=[3, 4], size=20)
# Triangle
[Link](x=[3], y=[5], size=30)
# Rectangle
[Link](x=[4], y=[2], width=1, height=2)
# Ellipse (instead of oval)
[Link](x=[5], y=[4], width=1.5, height=0.8)
# Show the plot
show(p)
Plotting Multiple Plots in Bokeh
Bokeh provides different layout methods to display multiple plots together in an organized way.

Types of Layouts
1. Vertical Layout
● Method: column()
● Arranges plots one below another (top to bottom)
Example structure: p = column(plot1, plot2, plot3)

2. Horizontal Layout
● Method: row()
● Arranges plots side by side (left to right)
Example structure: p = row(plot1, plot2, plot3)

3. Grid Layout
● Method: gridplot()
● Arranges plots in a grid (rows & columns)
Example structure: p = gridplot([[plot1, plot2], [plot3, None]])
None can be used to leave empty space
Horizontal Layout
Horizontal Layout set all the plots in the horizontal fashion. It can be created using the row() method.
Example:
from [Link] import output_file, show
from [Link] import row
from [Link] import figure
x = [1, 2, 3, 4, 5, 6]
y0 = x
y1 = [i * 2 for i in x]
y2 = [i ** 2 for i in x]
# create a new plot
s1 = figure(width =200, plot_height =200)
[Link](x, y0, size =10, alpha =0.5)
# create another one
s2 = figure(width =200, height =200)
[Link](x, y1, size =10, alpha =0.5)
# create and another
s3 = figure(width =200, height =200)
[Link](x, y2, size =10, alpha =0.5)
# put all the plots in a VBox
p = row(s1, s2, s3)
# show the results
show(p)

Output:
Interactive Data Visualization
One of the key features of Bokeh is to add interaction to the plots. Let's see various interactions that can be added.
Interactive Legends
click_policy property makes the legend interactive. There are two types of interactivity –
● Hiding: Hides the Glyphs.
● Muting: Hiding the glyph makes it vanish completely, on the other hand, muting the glyph just de-emphasizes the glyph based on the
parameters.

Example:
# importing the modules
from [Link] import figure, output_file, show
import pandas as pd

# instantiating the figure object


graph = figure(title = "Bokeh Bar Chart")
# reading the database
data = pd.read_csv("[Link]")
# plotting the graph
[Link](data['total_bill'], top=data['tip'],
legend_label = "Bill VS Tips", color='green')
[Link](data['tip'], top=data['size'],
legend_label = "Tips VS Size", color='red')
[Link].click_policy = "hide"
# displaying the model
show(graph)

Output:
Plotly for Data Visualization in Python

Plotly is a data visualization library that enables users to create interactive, publication ready charts and dashboards
in Python, R and JavaScript. It is widely used for exploratory data analysis, business reporting and web‑based
visualisations.

● Built on top of the Plotly JavaScript library ([Link]).


● Creates interactive charts like line plots, bar charts, scatter plots and maps
● Works seamlessly with Python libraries such as NumPy and Pandas
To install it type the below command in the terminal.
pip install plotly
Understanding Plotly Modules
Plotly consists of two key modules:
1. plotly.graph_objects: Low-level API of Plotly that contains objects such as Figure, layout and data which
are responsible for plotting.
2. [Link]: This is a high-level interface that simplifies the process of creating complex visualizations
and and automatic styling.
Example:
import [Link] as px

fig = [Link](x=[1, 2], y=[3, 4])

print(fig)
#[Link]()

Output:
1. Line chart
Plotly line chart is one of the simple plots where a line is drawn to show relation between the X-axis and Y-axis. It can be created using the [Link]()
method with each data position is represented as a vertex of a polyline mark in 2D space.
Syntax:
[Link](data_frame=None, x=None, y=None, color=None, title=None)
Parameters:
● data_frame: Dataset to plot.
● x: Column name for the X-axis.
● y: Column name for the Y-axis.
● color: Color the lines based on this column.
● title: Title of the plot.

Return: A [Link] object.


Example: We will be using Iris dataset and it is directly available as part of scikit-learn. df = [Link]() from the [Link] library loads it into a
Pandas DataFrame.
import [Link] as px
df = [Link]()
fig = [Link](df, y="sepal_width",)
[Link]()

Output:
In the above example, we can see that:
● Plotly automatically assigns labels to the X and Y axes.
● The data points for both axes are displayed.
● We can zoom in, zoom out or select specific parts of the data.
● It provides interactive tools in the top-right corner for chart manipulation.
● We can also save the chart locally as a static image.
Example 1: In this example we will use the line dash parameter which is used to group the lines according to the
dataframe column passed.
import [Link] as px

df = [Link]()

fig = [Link](df, y="sepal_width", line_group='species')

[Link]()

Output:
Example 2: In this example, we will group and color the data according to the species. We will also change the line
format. For this we will use two attributes such line_dash and color.
import [Link] as px

df = [Link]()

fig = [Link](df, y="sepal_width", line_dash='species',


color='species')

[Link]()

Output:
Example:
import [Link] as px
import pandas as pd

# reading the database


data = pd.read_csv("[Link]")

# plotting the scatter chart


fig = [Link](data, y='tip', color='sex')

# showing the plot


[Link]()

Output:
2. Bar Chart
A bar chart is a pictorial representation of data that presents categorical data with rectangular bars with heights or lengths
proportional to the values that they represent. These data sets contain the numerical values of variables that represent the length or
height. It can be created using the [Link]() method.
Syntax:
[Link](data_frame=None, x=None, y=None, color=None, title=None)
Parameters:
● data_frame: Dataset to plot.
● x: The column name for the X-axis.
● y: The column name for the Y-axis.
● color: Color the bars based on this column.
● title: Title of the plot.

Return: A [Link] object.


Example: We will be using tips dataset and this dataset contains
244 rows and 7 columns with each row representing a single restaurant
bill and associated information.
import [Link] as px
df = [Link]()
fig = [Link](df, x='day', y="total_bill")
[Link]()

Output:
Example:
import [Link] as px
import pandas as pd

# reading the database


data = pd.read_csv("[Link]")

# plotting the scatter chart


fig = [Link](data, x='day', y='tip', color='sex')

# showing the plot


[Link]()

Output:
3. Scatter Plot
A scatter plot is a set of dotted points to represent individual pieces of data in the horizontal and vertical axis. A graph in which the values of
two variables are plotted along X-axis and Y-axis, the pattern of the resulting points reveals a correlation between them and it can be created
using the [Link]() method.
Syntax:
[Link](data_frame=None, x=None, y=None, color=None, title=None)
Parameters:
● data_frame: Dataset to plot.
● x: The column name for the X-axis.
● y: The column name for the Y-axis.
● color: Color the bars based on this column.
● title: Title of the plot.

Return: A [Link] object.


Example:
import [Link] as px
df = [Link]()
fig = [Link](df, x ='total_bill' , y="tip")
[Link]()

Output:
Example:
import [Link] as px
import pandas as pd

# reading the database


data = pd.read_csv("[Link]")

# plotting the scatter chart


fig = [Link](data, x="day", y="tip", color='sex')

# showing the plot


[Link]()

Output:
4. Histogram
A histogram is used to represent data in the form of some groups. It is a type of bar plot where the X-axis represents the bin ranges
while the Y-axis gives information about frequency. It can be created using the [Link]() method.
Syntax:
[Link](data_frame=None, x=None, y=None, color=None, nbins=None, histnorm=None, title=None,
width=None, height=None)
Parameters:
● data_frame: Dataset to plot.
● x: The column name for the X-axis (values to be binned).
● color: Color the bars based on this column.
● nbins: Set the number of bins.
● histnorm: Normalize the histogram (e.g"percent", "density").

Return: A [Link] object.


Example:
import [Link] as px

df = [Link]()

fig = [Link](df, x ="total_bill")

[Link]()

Output:
Example:
import [Link] as px
import pandas as pd

# reading the database


data = pd.read_csv("[Link]")

# plotting the scatter chart


fig = [Link](data, x='total_bill', color='sex')

# showing the plot


[Link]()

Output:
5. Pie Chart
A pie chart is a circular statistical graphic which is divided into slices to show numerical proportions. It shows a special
chart that uses “pie slices” where each sector shows the relative sizes of data. It can be created using the [Link]() method.
Syntax:
[Link](data_frame=None, names=None, values=None, color=None, hole=None, title=None,
width=None, height=None)
Parameters:
● data_frame: Dataset to plot.
● names: Column name for the pie chart labels.
● values: Column name for the size of the slices.
● hole: Creates a donut chart when set between 0 and 1.

Return: A [Link] object.


Example:
import [Link] as px
df = [Link]()
fig = [Link](df, values="total_bill", names="day")
[Link]()

Output:
Let's customize the above graph.
● color_discrete_sequence: Strings defining valid CSS colors
● opacity: It finds how transparent or solid the markers (such as points on a
scatter plot) appear. The value should be between 0 and 1
● hole: Creates a hole in between to make it a donut chart. The value should be
between 0 and 1

import [Link] as px

df = [Link]()

fig = [Link](df, values="total_bill", names="day",


color_discrete_sequence=[Link],
opacity=0.7, hole=0.5)
[Link]()

Output:
8. 3D Scatter Plot
3D Scatter Plot shows data points in three dimensions, adding extra information by adjusting color, size and style of the points. These
adjustments help make the plot clearer and easier to understand. You can create a 3D scatter plot using the scatter_3d function from the
[Link] class.
Syntax:
[Link].scatter_3d(data_frame=None, x=None, y=None, z=None, color=None, symbol=None, size=None, title=None,
width=None, height=None)
Parameters:
● data_frame: Dataset to plot.
● x: The column name for the X-axis.
● y: The column name for the Y-axis.
● z: The column name for the Z-axis.
● color: Color the points based on this column.
● size: Size of the points.

Return: A [Link] object.


Example:
import [Link] as px
df = [Link]()
fig = px.scatter_3d(df, x ="total_bill" , y="sex", z="tip")
[Link]()

Output:
Adding interaction
Just like Bokeh, plotly also provides various interactions. Let's discuss a few of them.

Creating Dropdown Menu: A drop-down menu is a part of the menu-button which is displayed on a screen all the time.
Every menu button is associated with a Menu widget that can display the choices for that menu button when clicked on
it. In plotly, there are 4 possible methods to modify the charts by using updatemenu method.
● restyle: modify data or data attributes
● relayout: modify layout attributes
● update: modify data and layout attributes
● animate: start or pause an animation
Example:
import plotly.graph_objects as px
import pandas as pd
# reading the database
data = pd.read_csv("[Link]")

plot = [Link](data=[[Link](
x=data['day'],
y=data['tip'],
mode='markers',)
])
# Add dropdown
plot.update_layout(
updatemenus=[
dict(
buttons=list([
dict(
args=["type", "scatter"],
label="Scatter Plot",
method="restyle"
),
dict(
args=["type", "bar"],
label="Bar Chart",
method="restyle"
)
]),
direction="down",
),
]
)
[Link]()

Output:
Example:
Adding Buttons: In plotly, actions custom
import plotly.graph_objects as px
Buttons are used to quickly make actions directly import pandas as pd
from a record. Custom Buttons can be added to # reading the database
data = pd.read_csv("[Link]")
page layouts in CRM, Marketing, and Custom plot = [Link](data=[[Link](
Apps. There are also 4 possible methods that can x=data['day'],
y=data['tip'],
be applied in custom buttons: mode='markers',)
])
● restyle: modify data or data attributes # Add dropdown
plot.update_layout(
● relayout: modify layout attributes updatemenus=[
● update: modify data and layout dict(
type="buttons",
attributes direction="left",
● animate: start or pause an animation buttons=list([
dict(
args=["type", "scatter"],
label="Scatter Plot",
method="restyle"
),
dict(
args=["type", "bar"],
label="Bar Chart",
method="restyle"
)
]),
),
]
)
[Link]()

Output:
Creating Sliders and Selectors:
In plotly, the range slider is a custom range-type input control. It allows selecting a value or a range of values between a specified minimum and
maximum range. And the range selector is a tool for selecting ranges to display within the chart. It provides buttons to select pre-configured ranges in the
chart. It also provides input boxes where the minimum and maximum dates can be manually input
Example:
import plotly.graph_objects as px
import pandas as pd
# reading the database
data = pd.read_csv("[Link]")
plot = [Link](data=[[Link](
y=data['tip'],
mode='lines',)
])
plot.update_layout(
xaxis=dict(
rangeselector=dict(
buttons=list([
dict(count=1,
step="day",
stepmode="backward"),
])
),
rangeslider=dict(
visible=True
),
)
)
[Link]()

Output:

You might also like