Plotly is an open-source module of Python that is widely used for data visualization with Plotly, offering a variety of graph types such as line charts, scatter plots, bar charts, histograms, area plots, and more. In this article, we will explore plotting in Plotly, demonstrating how to create a basic chart and how to enhance it with Plotly interactive chart features. But before diving into the technicalities, let’s understand why it’s essential to learn Plotly visualizations.
Plotly uses javascript enabling data visualization using Plotly to be highly interactive, allowing users to zoom in, hover for data insights, and much more. Plotly graph visualization also provides several advantages, such as:
- Hover tool capabilities for detecting outliers or anomalies in vast datasets.
- Moreover, Plotly data visualization is visually appealing, making it accessible to a wide audience, and offers endless customization, which makes plots more meaningful and easier to comprehend for others.
Installing Plotly for Data Visualization
Plotly does not come built-in with Python. To install it type the below command in the terminal.
pip install plotly

Installing Plotly for Data Visualization
Understanding Plotly Modules – Introduction
In Plotly, there are three main modules:
- plotly.plotly acts as the interface between the local machine and Plotly. It contains functions that require a response from Plotly’s server.
- plotly.graph_objects module contains the objects (Figure, layout, data, and the definition of the plots like scatter plot, line chart) that are responsible for creating the plots. The Figure can be represented either as dict or instances of plotly.graph_objects.Figure and these are serialized as JSON before it gets passed to plotly.js. Figures are represented as trees where the root node has three top layer attributes – data, layout, and frames and the named nodes called ‘attributes’.
Note: plotly.express module can create the entire Figure at once. It uses the graph_objects internally and returns the graph_objects.Figure instance.
Example:
Python
import plotly.express as px
# Creating the Figure instance
fig = px.line(x=[1, 2], y=[3, 4])
# printing the figure instance
print(fig)
Output:

- plotly.tools module contains various tools in the forms of the functions that can enhance the Plotly experience.
After going through the basics of plotly let’s see how to create some basic charts using plotly.
Getting Started with Basic Charts in Plotly
In this section, we will explore how to generate basic charts using Plotly and apply various customizations to enhance their appearance and functionality. By the end of this section, you will have a solid understanding of how to create and customize basic visualizations, including line charts, scatter plots, bar charts, histograms, and pie charts. We will cover the following customizations:
- Adjusting chart layout
- Adding annotations
- Customizing markers and lines
Let’s dive into the code examples to see these customizations in action.
Plotly line chart is one of the simple plots where a line is drawn to shoe relation between the X-axis and Y-axis. It can be created using the px.line() method with each data position is represented as a vertex (which location is given by the x and y columns) of a polyline mark in 2D space.
Syntax:
Syntax: plotly.express.line(data_frame=None, x=None, y=None, line_group=None, color=None, line_dash=None, hover_name=None, hover_data=None, title=None, template=None, width=None, height=None)
Example:
Python
import plotly.express as px
# using the iris dataset
df = px.data.iris()
# plotting the line chart
fig = px.line(df, y="sepal_width",)
# showing the plot
fig.show()
Output:

In the above example, we can see that –
- The labels to the x-axis and y-axis have given automatically by plotly.
- The data of the x-axis and y-axis is shown on hover.
- We can also select a part of the data according to our needs and can also zoom out.
- Plotly also provides a set of tools (seen on the top right corner) to interact with every chart.
- Plotly also allows us to save the graph locally in a static format.
Now let’s try to customize our graph a little.
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.
Python
import plotly.express as px
# using the iris dataset
df = px.data.iris()
# plotting the line chart
fig = px.line(df, y="sepal_width", line_group='species')
# showing the plot
fig.show()
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.
Python
import plotly.express as px
# using the iris dataset
df = px.data.iris()
# plotting the line chart
fig = px.line(df, y="sepal_width", line_dash='species',
color='species')
# showing the plot
fig.show()
Output:

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. In other words, it is the pictorial representation of dataset. These data sets contain the numerical values of variables that represent the length or height. It can be created using the px.bar() method.
Syntax:
plotly.express.bar(data_frame=None, x=None, y=None, color=None, facet_row=None, facet_col=None, facet_col_wrap=0, hover_name=None, hover_data=None, custom_data=None, text=None, error_x=None, error_x_minus=None, error_y=None, error_y_minus=None, title=None, template=None, width=None, height=None, **kwargs)
Example:
Python
import plotly.express as px
# Loading the data
df = px.data.tips()
# Creating the bar chart
fig = px.bar(df, x='day', y="total_bill")
fig.show()
Output:

Let’s try to customize this plot. Customizations that we will use –
- color: Used to color the bars.
- facet_row: Divides the graph into rows according to the data passed
- facet_col: Divides the graph into columns according to the data passed
Example:
Python
import plotly.express as px
# Loading the data
df = px.data.tips()
# Creating the bar chart
fig = px.bar(df, x='day', y="total_bill", color='sex',
facet_row='time', facet_col='sex')
fig.show()
Output:

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 created using the px.scatter() method.
Syntax:
plotly.express.scatter(data_frame=None, x=None, y=None, color=None, symbol=None, size=None, hover_name=None, hover_data=None, facet_row=None, facet_col=None, facet_col_wrap=0, opacity=None, title=None, template=None, width=None, height=None, **kwargs)
Example:
Python
import plotly.express as px
# using the dataset
df = px.data.tips()
# plotting the scatter chart
fig = px.scatter(df, x='total_bill', y="tip")
# showing the plot
fig.show()
Output:

Let’s see various customizations available for this chart that we will use –
- color: Color the points.
- symbol: Gives a symbol to each point according to the data passed.
- size: The size for each point.
Example:
Python
import plotly.express as px
# using the dataset
df = px.data.tips()
# plotting the scatter chart
fig = px.scatter(df, x='total_bill', y="tip", color='time',
symbol='sex', size='size', facet_row='day',
facet_col='time')
# showing the plot
fig.show()
Output:

A histogram is basically 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 px.histogram() method.
Syntax:
plotly.express.histogram(data_frame=None, x=None, y=None, color=None, facet_row=None, facet_col=None, barnorm=None, histnorm=None, nbins=None, title=None, template=None, width=None, height=None)
Example:
Python
import plotly.express as px
# using the dataset
df = px.data.tips()
# plotting the histogram
fig = px.histogram(df, x="total_bill")
# showing the plot
fig.show()
Output:

Let’s customize the above graph. Customizations that we will be using are –
- color: To color the bars
- nbins: To set the number of bins
- histnorm: Mode through which the bins are represented. Different values that can be passed using this argument are-
- percent or probability: The output of histfunc for a given bin is divided by the sum of the output of histfunc for all bins.
- density: The output of histfunc for a given bin is divided by the size of the bin.
- probability density: The output of histfunc for a given bin is normalized such that it corresponds to the probability that a random
- barmode: Can be either ‘group’, ‘overlay’ or ‘relative’.
- group: Bars are stacked above zero for positive values and below zero for negative values
- overlay: Bars are drawn on the top of each other
- group: Bars are placed beside each other.
Example:
Python
import plotly.express as px
# using the dataset
df = px.data.tips()
# plotting the histogram
fig = px.histogram(df, x="total_bill", color='sex',
nbins=50, histnorm='percent',
barmode='overlay')
# showing the plot
fig.show()
Output:

A pie chart is a circular statistical graphic, which is divided into slices to illustrate numerical proportions. It depicts a special chart that uses “pie slices”, where each sector shows the relative sizes of data. A circular chart cuts in a form of radii into segments describing relative frequencies or magnitude also known as a circle graph. It can be created using the px.pie() method.
Syntax:
plotly.express.pie(data_frame=None, names=None, values=None, color=None, color_discrete_sequence=None, color_discrete_map={}, hover_name=None, hover_data=None, custom_data=None, labels={}, title=None, template=None, width=None, height=None, opacity=None, hole=None)
Example:
Python
import plotly.express as px
# Loading the iris dataset
df = px.data.tips()
fig = px.pie(df, values="total_bill", names="day")
fig.show()
Output:

Let’s customize the above graph. Customizations that we will be using are –
- color_discrete_sequence: Strings defining valid CSS colors
- opacity: Opacity for markers. 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
Example:
Python
import plotly.express as px
# Loading the iris dataset
df = px.data.tips()
fig = px.pie(df, values="total_bill", names="day",
color_discrete_sequence=px.colors.sequential.RdBu,
opacity=0.7, hole=0.5)
fig.show()
Output:

A Box Plot is also known as Whisker plot is created to display the summary of the set of data values having properties like minimum, first quartile, median, third quartile and maximum. In the box plot, a box is created from the first quartile to the third quartile, a vertical line is also there which goes through the box at the median. Here x-axis denotes the data to be plotted while the y-axis shows the frequency distribution. It can be created using the px.box() method
Syntax:
plotly.express.box(data_frame=None, x=None, y=None, color=None, facet_row=None, facet_col=None, title=None, template=None, width=None, height=None, **kwargs)
Example:
Python
import plotly.express as px
# using the dataset
df = px.data.tips()
# plotting the boxplot
fig = px.box(df, x="day", y="tip")
# showing the plot
fig.show()
Output:

Let’s see various customizations that can be used on boxplots –
- color: used to assign color to marks
- facet_row: assign marks to facetted subplots in the vertical direction
- facet_col: assign marks to facetted subplots in the horizontal direction
- boxmode: One of ‘group’ or ‘overlay’ In ‘overlay’ mode, boxes are on drawn top of one another. In ‘group’ mode, boxes are placed beside each other.
- notched: If True, boxes are drawn with notches
Example:
Python
import plotly.express as px
# using the dataset
df = px.data.tips()
# plotting the boxplot
fig = px.box(df, x="day", y="tip", color='sex',
facet_row='time', boxmode='group',
notched=True)
# showing the plot
fig.show()
Output:

Violin Plot is a method to visualize the distribution of numerical data of different variables. It is similar to Box Plot but with a rotated plot on each side, giving more information about the density estimate on the y-axis. The density is mirrored and flipped over and the resulting shape is filled in, creating an image resembling a violin. The advantage of a violin plot is that it can show nuances in the distribution that aren’t perceptible in a boxplot. On the other hand, the boxplot more clearly shows the outliers in the data. It can be created using the px.violin() method.
Syntax:
violin(data_frame=None, x=None, y=None, color=None, facet_row=None, facet_col=None, facet_col_wrap=0, facet_row_spacing=None, facet_col_spacing=None, hover_name=None, hover_data=None, title=None, template=None, width=None, height=None, **kwargs)
Example:
Python
import plotly.express as px
# using the dataset
df = px.data.tips()
# plotting the violin plot
fig = px.violin(df, x="day", y="tip")
# showing the plot
fig.show()
Output:

For customizing the violin plot we will use the same customizations available for the box plot except the boxmode and notched which are not available for the violin plot. We will also the box parameter. Setting this parameter to True will show a box plot inside the violin plot.
Example:
Python
import plotly.express as px
# using the dataset
df = px.data.tips()
# plotting the violin plot
fig = px.violin(df, x="day", y="tip", color='sex',
facet_row='time', box=True)
# showing the plot
fig.show()
Output:

3D Scatter Plot can plot two-dimensional graphics that can be enhanced by mapping up to three additional variables while using the semantics of hue, size, and style parameters. All the parameter control visual semantic which are used to identify the different subsets. Using redundant semantics can be helpful for making graphics more accessible. It can be created using the scatter_3d function of plotly.express class.
Syntax:
plotly.express.scatter_3d(data_frame=None, x=None, y=None, z=None, color=None, symbol=None, size=None, range_x=None, range_y=None, range_z=None, title=None, template=None, width=None, height=None, **kwargs)
Example:
Python
import plotly.express as px
# data to be plotted
df = px.data.tips()
# plotting the figure
fig = px.scatter_3d(df, x="total_bill", y="sex", z="tip")
fig.show()
Output:

Customizing the 3D scatter plot. We will use the following customization –
- color: Set the color of the markers
- size: Set the size of the marker
- symbol: Set the symbol of the plot
Example:
Python
import plotly.express as px
# data to be plotted
df = px.data.tips()
# plotting the figure
fig = px.scatter_3d(df, x="total_bill", y="sex", z="tip", color='day',
size='total_bill', symbol='time')
fig.show()
Output:

Implementing Interactive Features to the Plots
Every graph created by the plotly provides various interactions, where we can select a part of the plot, we get information on hovering over the plot, and also a toolbar is also created with every plot that can many tasks like saving the plot locally or zooming in and out, etc. Besides all these plotly allows us to add more tools like dropdowns, buttons, sliders, etc. These can be created using the update menu attribute of the plot layout. Let’s see how to do all such things in detail.
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 update menu method.
- restyle: modify data or data attributes
- relayout: modify layout attributes
- update: modify data and layout attributes
- animate: start or pause an animation
Example:
Python
import plotly.graph_objects as px
import numpy as np
import pandas as pd
df = pd.read_csv('tips.csv')
plot = px.Figure(data=[px.Scatter(
x=df['day'],
y=df['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",
),
]
)
plot.show()
Output:

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

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:
Python
import plotly.graph_objects as px
import plotly.express as go
import numpy as np
df = go.data.tips()
x = df['total_bill']
y = df['tip']
plot = px.Figure(data=[px.Scatter(
x=x,
y=y,
mode='markers',)
])
plot.update_layout(
xaxis=dict(
rangeselector=dict(
buttons=list([
dict(count=1,
step="day",
stepmode="backward"),
])
),
rangeslider=dict(
visible=True
),
)
)
plot.show()
Output:

Plotly Dash is a powerful framework for building interactive web applications with Python. It allows you to create dynamic and visually appealing dashboards that can handle complex interactions and data visualizations. In this section, we will explore the essentials of building interactive dashboards using Plotly Dash.
For more advanced interactive applications, you can use Plotly Dash to create dashboards. Here’s a basic example of a Dash app:
1. Install the necessary packages:
!pip install dash jupyter-dash plotly pandas
2. Use the JupyterDash class to create and run the Dash:
Python
import dash
from dash import dcc, html
import plotly.express as px
import pandas as pd
from jupyter_dash import JupyterDash
# Sample data
df = pd.DataFrame({
'x': [1, 2, 3, 4, 5],
'y': [10, 15, 13, 17, 14]
})
# Create a Dash app
app = JupyterDash(__name__)
app.layout = html.Div([
dcc.Graph(
id='example-graph',
figure=px.scatter(df, x='x', y='y', title='Scatter Plot in Dash')
)
])
# Run the app
app.run_server(mode='inline')
Output:

Creating Dashboards
Conclusion
Plotly provides a rich set of tools for creating interactive visualizations in Python. From basic charts to complex interactive dashboards, Plotly’s capabilities allow you to create visually appealing and functional data presentations. By customizing your charts and using interactive features, you can enhance your data exploration and communication.
Similar Reads
Python - Data visualization tutorial
Data visualization is a crucial aspect of data analysis, helping to transform analyzed data into meaningful insights through graphical representations. This comprehensive tutorial will guide you through the fundamentals of data visualization using Python. We'll explore various libraries, including M
7 min read
What is Data Visualization and Why is It Important?
Data visualization is the graphical representation of information and data. By using visual elements like charts, graphs, and maps, data visualization tools provide an accessible way to see and understand trends, outliers, and patterns in data. This practice is crucial in the data science process, a
13 min read
Data Visualization using Matplotlib in Python
Data visualization is a crucial aspect of data analysis, enabling data scientists and analysts to present complex data in a more understandable and insightful manner. One of the most popular libraries for data visualization in Python is Matplotlib. In this article, we will provide a comprehensive gu
15+ min read
Data Visualization with Seaborn - Python
Data Visualization is the presentation of data in pictorial format. It is extremely important for Data Analysis, primarily because of the fantastic ecosystem of data-centric Python packages. And it helps to understand the data, however, complex it is, the significance of data by summarizing and pres
15 min read
Data Visualization with Pandas
Data Visualization with Pandas is the presentation of data in a graphical format. It helps people understand the significance of data by summarizing and presenting a huge amount of data in a simple and easy-to-understand format and helps communicate information clearly and effectively. In this tutor
14 min read
Plotly for Data Visualization in Python
Plotly is an open-source module of Python that is widely used for data visualization with Plotly, offering a variety of graph types such as line charts, scatter plots, bar charts, histograms, area plots, and more. In this article, we will explore plotting in Plotly, demonstrating how to create a bas
15 min read
Data Visualization using Plotnine and ggplot2 in Python
Data Visualization is the technique of presenting data in the form of graphs, charts, or plots. Visualizing data makes it easier for the data analysts to analyze the trends or patterns that may be present in the data as it summarizes the huge amount of data in a simple and easy-to-understand format.
10 min read
Introduction to Altair in Python
Altair is a statistical visualization library in Python. It is a declarative in nature and is based on Vega and Vega-Lite visualization grammars. It is fast becoming the first choice of people looking for a quick and efficient way to visualize datasets. If you have used imperative visualization libr
5 min read
Python - Data visualization using Bokeh
Bokeh is a data visualization library in Python that provides high-performance interactive charts and plots. Bokeh output can be obtained in various mediums like notebook, html and server. It is possible to embed bokeh plots in Django and flask apps. Bokeh provides two visualization interfaces to us
3 min read
Pygal Introduction
Python has become one of the most popular programming languages for data science because of its vast collection of libraries. In data science, data visualization plays a crucial role that helps us to make it easier to identify trends, patterns, and outliers in large data sets. Pygal is best suited f
5 min read
Jobs Related to Data Visualization
Data presentation visually, such as graphs, charts, and infographics, is a vital area of study known as data visualization. People may make better judgments and comprehend difficult information more efficiently with these visual aids. The need for experts with data visualization skills has grown alo
5 min read
How to Get an Internship as a Data Visualization Specialist
As companies increasingly recognize the value of data-driven decision-making, the demand for skilled data visualization specialists continues to grow. This role not only provides excellent career prospects but also allows professionals to work on diverse and interesting projects, from business analy
7 min read