Plotly Tutorial
Plotly Tutorial
CoursesTutorialsData SciencePractice
Python Basics Interview Questions Python Quiz Popular Packages Python Projects Practice Python AI Wit
Plotly tutorial
Last Updated : 26 Dec, 2023
Plotly library in Python is an open-source library that can be used for data
visualization and understanding data simply and easily. Plotly supports various
types of plots like line charts, scatter plots, histograms, box plots, etc. So you
all must be wondering why Plotly is over other visualization tools or libraries.
So here are some reasons :
Plotly has hover tool capabilities that allow us to detect any outliers or
anomalies in a large number of data points.
It is visually attractive and can be accepted by a wide range of audiences.
Plotly generally allows us endless customization of our graphs and makes
our plot more meaningful and understandable for others.
This tutorial aims at providing you the insight about Plotly with the help of the
huge dataset explaining the Plotly from basics to advance and covering all the
popularly used charts.
Table of Content
How to install Plotly?
Package Structure of Plotly
https://www.geeksforgeeks.org/python-plotly-tutorial/ 1/32
7/11/24, 9:29 AM Plotly tutorial - GeeksforGeeks
Getting Started
Creating Different Types of Charts
Heatmaps
Error Bars
3D Line Plots
3D Scatter Plot Plotly
3D Surface Plots
Interacting with the Plots
Adding Buttons to the Plot
Creating Sliders and Selectors to the Plot
More Plots using Plotly
How to install Plotly?
Before installing Plotly in system, you need to install pip in your system, Refer
to –
Plotly does not come built-in with Python. To install it type the below
command in the terminal.
This may take some time as it will install the dependencies as well.
https://www.geeksforgeeks.org/python-plotly-tutorial/ 2/32
7/11/24, 9:29 AM Plotly tutorial - GeeksforGeeks
plotly.plotly
plotly.graph.objects
plotly.tools
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. Consider the below example for better understanding.
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:
Python3
import plotly.express as px
Output:
Figure({
'data': [{'hovertemplate': 'x=%{x}<br>y=%{y}<extra></extra>',
'legendgroup': '',
'line': {'color': '#636efa', 'dash': 'solid'},
'marker': {'symbol': 'circle'},
https://www.geeksforgeeks.org/python-plotly-tutorial/ 3/32
7/11/24, 9:29 AM Plotly tutorial - GeeksforGeeks
'mode': 'lines',
'name': '',
'orientation': 'v',
'showlegend': False,
'type': 'scatter',
'x': array([1, 2, 3]),
'xaxis': 'x',
'y': array([1, 2, 3]),
'yaxis': 'y'}],
'layout': {'legend': {'tracegroupgap': 0},
'margin': {'t': 60},
'template': '...',
'xaxis': {'anchor': 'y', 'domain': [0.0, 1.0], 'title':
{'text': 'x'}},
'yaxis': {'anchor': 'x', 'domain': [0.0, 1.0], 'title':
{'text': 'y'}}}
})
Figures are represented as trees where the root node has three top layer
attributes – data, layout, and frames and the named nodes called ‘attributes’.
Consider the above example, layout.legend is a nested dictionary where the
legend is the key inside the dictionary whose value is also a dictionary.
plotly.tools module contains various tools in the forms of the functions that
can enhance the Plotly experience.
Getting Started
After learning the installation and basic structure of the Plotly, let’s create a
simple plot using the pre-defined data sets defined by the plotly.
Example:
Python3
import plotly.express as px
https://www.geeksforgeeks.org/python-plotly-tutorial/ 4/32
7/11/24, 9:29 AM Plotly tutorial - GeeksforGeeks
fig.show()
Output:
In the above example, the plotly.express module is imported which returns the
Figure instance. We have created a simple line chart by passing the x, y
coordinates of the points to be plotted.
Line Chart
Line plot in Plotly is much accessible and illustrious annexation to plotly which
manage a variety of types of data and assemble easy-to-style statistic. With
px.line 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.
Example:
Python3
import plotly.express as px
https://www.geeksforgeeks.org/python-plotly-tutorial/ 5/32
7/11/24, 9:29 AM Plotly tutorial - GeeksforGeeks
df = px.data.iris()
Output:
Refer to the below articles to get detailed information about the line charts.
Bar Chart
Example:
Python3
import plotly.express as px
https://www.geeksforgeeks.org/python-plotly-tutorial/ 6/32
7/11/24, 9:29 AM Plotly tutorial - GeeksforGeeks
Output:
Refer to the below articles to get detailed information about the bar chart.
Histograms
Example:
Python3
https://www.geeksforgeeks.org/python-plotly-tutorial/ 7/32
7/11/24, 9:29 AM Plotly tutorial - GeeksforGeeks
import plotly.express as px
Output:
Refer to the below articles to get detailed information about the histograms.
https://www.geeksforgeeks.org/python-plotly-tutorial/ 8/32
7/11/24, 9:29 AM Plotly tutorial - GeeksforGeeks
A bubble plot is a scatter plot with bubbles (color-filled circles). Bubbles have
various sizes dependent on another variable in the data. It can be created using
the scatter() method of plotly.express.
Python3
import plotly.express as px
Output:
Python3
import plotly.express as px
https://www.geeksforgeeks.org/python-plotly-tutorial/ 9/32
7/11/24, 9:29 AM Plotly tutorial - GeeksforGeeks
df = px.data.iris()
Output:
Refer to the below articles to get detailed information about the scatter plots
and bubble plots.
Pie Charts
https://www.geeksforgeeks.org/python-plotly-tutorial/ 10/32
7/11/24, 9:29 AM Plotly tutorial - GeeksforGeeks
Example:
Python3
import plotly.express as px
Output:
Refer to the below articles to get detailed information about the pie charts.
Box Plots
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
https://www.geeksforgeeks.org/python-plotly-tutorial/ 11/32
7/11/24, 9:29 AM Plotly tutorial - GeeksforGeeks
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.
Example:
Python3
import plotly.express as px
Output:
Refer to the below articles to get detailed information about box plots.
https://www.geeksforgeeks.org/python-plotly-tutorial/ 12/32
7/11/24, 9:29 AM Plotly tutorial - GeeksforGeeks
Violin plots
Example:
Python3
import plotly.express as px
Output:
https://www.geeksforgeeks.org/python-plotly-tutorial/ 13/32
7/11/24, 9:29 AM Plotly tutorial - GeeksforGeeks
Refer to the below articles to get detailed information about the violin plots
Gantt Charts
Example:
Python3
import plotly.figure_factory as ff
# Data to be plotted
df = [dict(Task="A", Start='2020-01-01', Finish='2009-02-02'),
dict(Task="Job B", Start='2020-03-01', Finish='2020-11-11'),
dict(Task="Job C", Start='2020-08-06', Finish='2020-09-21')]
Output:
https://www.geeksforgeeks.org/python-plotly-tutorial/ 14/32
7/11/24, 9:29 AM Plotly tutorial - GeeksforGeeks
Refer to the below articles to get detailed information about the Gantt Charts.
Contour Plots
A Contour plots also called level plots are a tool for doing multivariate
analysis and visualizing 3-D plots in 2-D space. If we consider X and Y as our
variables we want to plot then the response Z will be plotted as slices on the
X-Y plane due to which contours are sometimes referred as Z-slices or iso-
response.
A contour plots is used in the case where you want to see the changes in some
value (Z) as a function with respect to the two values (X, Y). Consider the
below example.
Example:
Python3
import plotly.graph_objects as go
https://www.geeksforgeeks.org/python-plotly-tutorial/ 15/32
7/11/24, 9:29 AM Plotly tutorial - GeeksforGeeks
Z = np.cos(X / 2) + np.sin(Y / 4)
fig.show()
Output:
Refer to the below articles to get detailed information about contour plots.
Heatmaps
Heatmap is defined as a graphical representation of data using colors to
visualize the value of the matrix. In this, to represent more common values or
higher activities brighter colors basically reddish colors are used and to
represent less common or activity values, darker colors are preferred. Heatmap
is also defined by the name of the shading matrix.
Example:
https://www.geeksforgeeks.org/python-plotly-tutorial/ 16/32
7/11/24, 9:29 AM Plotly tutorial - GeeksforGeeks
Python3
import plotly.graph_objects as go
Z = np.cos(X / 2) + np.sin(Y / 4)
fig.show()
Output:
Refer to the below articles to get detailed information about the heatmaps.
Error Bars
https://www.geeksforgeeks.org/python-plotly-tutorial/ 17/32
7/11/24, 9:29 AM Plotly tutorial - GeeksforGeeks
Example:
Python3
import plotly.express as px
Output:
3D Line Plots
https://www.geeksforgeeks.org/python-plotly-tutorial/ 18/32
7/11/24, 9:29 AM Plotly tutorial - GeeksforGeeks
Line plot in plotly is much accessible and illustrious annexation to plotly which
manage a variety of types of data and assemble easy-to-style statistic. With
px.line_3d each data position is represented as a vertex (which location is
given by the x, y and z columns) of a polyline mark in 3D space.
Example:
Python3
import plotly.express as px
# data to be plotted
df = px.data.tips()
fig.show()
Output:
Refer to the below articles to get detailed information about the 3D line charts.
https://www.geeksforgeeks.org/python-plotly-tutorial/ 19/32
7/11/24, 9:29 AM Plotly tutorial - GeeksforGeeks
Example:
Python3
import plotly.express as px
# Data to be plotted
df = px.data.iris()
fig.show()
Output:
https://www.geeksforgeeks.org/python-plotly-tutorial/ 20/32
7/11/24, 9:29 AM Plotly tutorial - GeeksforGeeks
Refer to the below articles to get detailed information about the 3D scatter
plot.
3D Surface Plots
Surface plot is those plot which has three-dimensions data which is X, Y, and
Z. Rather than showing individual data points, the surface plot has a functional
relationship between dependent variable Y and have two independent
variables X and Z. This plot is used to distinguish between dependent and
independent variables.
Example:
Python3
import plotly.graph_objects as go
import numpy as np
# Data to be plotted
x = np.outer(np.linspace(-2, 2, 30), np.ones(30))
y = x.copy().T
z = np.cos(x ** 2 + y ** 2)
fig.show()
Output:
https://www.geeksforgeeks.org/python-plotly-tutorial/ 21/32
7/11/24, 9:29 AM Plotly tutorial - GeeksforGeeks
Example:
Python3
import plotly.graph_objects as px
import numpy as np
# creating random data through randomint
# function of numpy.random
np.random.seed(42)
https://www.geeksforgeeks.org/python-plotly-tutorial/ 22/32
7/11/24, 9:29 AM Plotly tutorial - GeeksforGeeks
# Data to be Plotted
random_x = np.random.randint(1, 101, 100)
random_y = np.random.randint(1, 101, 100)
plot = px.Figure(data=[px.Scatter(
x=random_x,
y=random_y,
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:
https://www.geeksforgeeks.org/python-plotly-tutorial/ 23/32
7/11/24, 9:29 AM Plotly tutorial - GeeksforGeeks
Output
In the above example we have created two graphs for the same data. These
plots are accessible using the dropdown menu.
Example:
Python3
import plotly.graph_objects as px
import pandas as pd
df = go.data.tips()
plot = px.Figure(data=[px.Scatter(
x=data['day'],
y=data['tip'],
mode='markers',)
https://www.geeksforgeeks.org/python-plotly-tutorial/ 24/32
7/11/24, 9:29 AM Plotly tutorial - GeeksforGeeks
])
# 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 this example also we are creating two different plots on the same data and
both plots are accessible by the buttons.
Example:
Python3
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['day']
plot = px.Figure(data=[px.Scatter(
x=x,
y=y,
mode='lines',)
])
plot.update_layout(
xaxis=dict(
rangeselector=dict(
buttons=list([
dict(count=1,
step="day",
stepmode="backward"),
])
),
rangeslider=dict(
visible=True
),
)
)
plot.show()
https://www.geeksforgeeks.org/python-plotly-tutorial/ 26/32
7/11/24, 9:29 AM Plotly tutorial - GeeksforGeeks
Output:
Output
https://www.geeksforgeeks.org/python-plotly-tutorial/ 27/32
7/11/24, 9:29 AM Plotly tutorial - GeeksforGeeks
Ready to dive into the future? Mastering Generative AI and ChatGPT is your
gateway to the cutting-edge world of AI. Perfect for tech enthusiasts, this
course will teach you how to leverage Generative AI and ChatGPT with
hands-on, practical lessons. Transform your skills and create innovative AI
applications that stand out. Don't miss out on becoming an AI expert – Enroll
now and start shaping the future!
GeeksforGeeks 7
Next Article
Introduction to Plotly-online using Python
https://www.geeksforgeeks.org/python-plotly-tutorial/ 28/32
7/11/24, 9:29 AM Plotly tutorial - GeeksforGeeks
Similar Reads
How to hide legend with Plotly Express and Plotly in Python?
In this article, we will learn How to hide legend with Plotly Express and Plotly.
Here we will discuss two different methods for hiding legend in plotly and plotl…
2 min read
Define Colors in a Figure Using Plotly Graph Objects and Plotly Express
Whether you use Plotly Graph Objects or Plotly Express, defining colors in your
figures allows you to create visually appealing and informative visualizations.…
3 min read
https://www.geeksforgeeks.org/python-plotly-tutorial/ 29/32
7/11/24, 9:29 AM Plotly tutorial - GeeksforGeeks
https://www.geeksforgeeks.org/python-plotly-tutorial/ 30/32
7/11/24, 9:29 AM Plotly tutorial - GeeksforGeeks
Company Explore
About Us Job-A-Thon Hiring Challenge
Legal Hack-A-Thon
Careers GfG Weekly Contest
In Media Offline Classes (Delhi/NCR)
Contact Us DSA in JAVA/C++
Advertise with us Master System Design
GFG Corporate Solution Master CP
Placement Training Program GeeksforGeeks Videos
Geeks Community
Languages DSA
Python Data Structures
Java Algorithms
C++ DSA for Beginners
PHP Basic DSA Problems
GoLang DSA Roadmap
SQL DSA Interview Questions
R Language Competitive Programming
Android Tutorial
https://www.geeksforgeeks.org/python-plotly-tutorial/ 31/32
7/11/24, 9:29 AM Plotly tutorial - GeeksforGeeks
DevOps Roadmap System Design Bootcamp
Interview Questions
https://www.geeksforgeeks.org/python-plotly-tutorial/ 32/32