Professional Documents
Culture Documents
Creating and Updating Figures - Python - Plotly PDF
Creating and Updating Figures - Python - Plotly PDF
Python
New to Plotly?
Representing Figures
Figures as dictionaries
The goal of plotly.py is to provide a pleasant Python interface for creating gure speci cations
for display in the Plotly.js JavaScript library. In Plotly.js, a gure is speci ed by a declarative
JSON data structure, and so the ultimate responsibility of plotly.py is to produce Python
dictionaries that can be serialized into a JSON data structure that represents a valid gure.
As a concrete example, here is a Python dictionary that represents a gure containing a single
bar trace and a title.
https://plot.ly/python/creating-and-updating-figures/ 1/43
2020/2/6 Creating and Updating Figures | Python | Plotly
fig = {
"data": [{"type": "bar",
"x": [1, 2, 3],
"y": [1, 3, 2]}],
"layout": {"title": {"text": "A Bar Chart"}}
}
# To display the figure defined by this dict, use the low-level plotly.i
o.show function
import plotly.io as pio
pio.show(fig)
A Bar Chart
2.5
1.5
https://plot.ly/python/creating-and-updating-figures/ 2/43
2020/2/6 Creating and Updating Figures | Python | Plotly
The value of the top-level "data" key is a list of trace speci cations. Each trace speci cation
has a special "type" key that indicates the trace type that is being de ned (e.g. a "bar",
"scatter", "contour", etc.). The rest of the keys in the trace speci cation are used to
con gure the properties of the trace of this type.
The value of the top-level "layout" key is a dictionary that speci es the properties of the
gure's layout. In contrast to trace con guration options that apply to individual traces, the
layout con guration options apply to the gure as a whole, customizing items like the axes,
annotations, shapes, legend, and more.
The Full Reference page contains descriptions of all of the supported trace and layout options.
If working from the Full Reference to build gures as Python dictionaries and lists suites your
needs, go for it! This is a perfectly valid way to use plotly.py to build gures. On the other
hand, if you would like an API that o ers a bit more assistance, read on to learn about graph
objects.
1. Graph objects provide precise data validation. So if you provide an invalid property
name or an invalid property value, an exception will be raised with a helpful error
message describing the problem.
2. Graph objects contain descriptions of each property as Python docstrings. You can use
these docstrings to learn about the available properties as an alternative to consulting
the Full Reference.
3. Properties of graph objects can be accessed using dictionary-style key lookup (e.g.
fig["layout"]) or class-style property access (e.g. fig.layout).
4. Graph objects support higher-level convenience functions for making updates to
already constructed gures, as described below.
https://plot.ly/python/creating-and-updating-figures/ 3/43
2020/2/6 Creating and Updating Figures | Python | Plotly
import plotly.graph_objects as go
fig = go.Figure(
data=[go.Bar(x=[1, 2, 3], y=[1, 3, 2])],
layout=go.Layout(
title=go.layout.Title(text="A Bar Chart")
)
)
fig.show()
A Bar Chart
2.5
1.5
You can also create a graph object gure from a dictionary representation by passing the
dictionary to the gure constructor.
https://plot.ly/python/creating-and-updating-figures/ 4/43
2020/2/6 Creating and Updating Figures | Python | Plotly
import plotly.graph_objects as go
fig = go.Figure({
"data": [{"type": "bar",
"x": [1, 2, 3],
"y": [1, 3, 2]}],
"layout": {"title": {"text": "A Bar Chart"}}
})
fig.show()
A Bar Chart
2.5
1.5
https://plot.ly/python/creating-and-updating-figures/ 5/43
2020/2/6 Creating and Updating Figures | Python | Plotly
Once you have a gure as a graph object, you can retrieve the dictionary representation using
the fig.to_dict() method. You can also retrieve the JSON string representation using the
fig.to_json() method.
Creating gures
This section summarizes several ways to create new graph object gures with plotly.py
Constructor
As demonstrated above, you can build a complete gure by passing trace and layout
speci cations to the plotly.graph_objects.Figure constructor. These trace and layout
speci cations can be either dictionaries or graph objects. Here, for example, the traces are
speci ed using graph objects and the layout is speci ed as a dictionary.
https://plot.ly/python/creating-and-updating-figures/ 6/43
2020/2/6 Creating and Updating Figures | Python | Plotly
import plotly.graph_objects as go
fig = go.Figure(
data=[go.Bar(x=[1, 2, 3], y=[1, 3, 2])],
layout=dict(title=dict(text="A Bar Chart"))
)
fig.show()
A Bar Chart
2.5
1.5
Plotly express
Plotly express (included as the plotly.express module) is a high-level data exploration API
that produces graph object gures.
https://plot.ly/python/creating-and-updating-figures/ 7/43
2020/2/6 Creating and Updating Figures | Python | Plotly
import plotly.express as px
df = px.data.iris()
fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species")
# If you print fig, you'll see that it's just a regular figure with data
and layout
# print(fig)
fig.show()
7.5
6.5
sepal_length
5.5
https://plot.ly/python/creating-and-updating-figures/ 8/43
2020/2/6 Creating and Updating Figures | Python | Plotly
Figure factories
Figure factories (included in plotly.py in the plotly.figure_factory module) are functions
that produce graph object gures, often to satisfy the needs of specialized domains. Here's an
example of using the create_quiver gure factory to construct a graph object gure that
displays a 2D quiver plot.
import numpy as np
import plotly.figure_factory as ff
x1,y1 = np.meshgrid(np.arange(0, 2, .2), np.arange(0, 2, .2))
u1 = np.cos(x1)*y1
v1 = np.sin(x1)*y1
1.5
https://plot.ly/python/creating-and-updating-figures/ 9/43
2020/2/6 Creating and Updating Figures | Python | Plotly
Make subplots
The plotly.subplots.make_subplots function produces a graph object gure that is
precon gured with a grid of subplots that traces can be added to. The add_trace function
will be discussed more below.
4 3
3.5 2.5
3 2
2.5
1.5
2
1
https://plot.ly/python/creating-and-updating-figures/ 10/43
2020/2/6 Creating and Updating Figures | Python | Plotly
Updating gures
Regardless of how a graph object gure was constructed, it can be updated by adding
additional traces and modifying its properties.
Adding traces
New traces can be added to a graph object gure using the add_trace method. This method
accepts a graph object trace (an instance of go.Scatter, go.Bar, etc.) and adds it to the
gure. This allows you to start with an empty gure, and add traces to it sequentially.
https://plot.ly/python/creating-and-updating-figures/ 11/43
2020/2/6 Creating and Updating Figures | Python | Plotly
import plotly.graph_objects as go
fig = go.Figure()
fig.add_trace(go.Bar(x=[1, 2, 3], y=[1, 3, 2]))
fig.show()
2.5
1.5
You can also add traces to a gure produced by a gure factory or Plotly Express.
https://plot.ly/python/creating-and-updating-figures/ 12/43
2020/2/6 Creating and Updating Figures | Python | Plotly
import plotly.express as px
df = px.data.iris()
fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species")
fig.add_trace(
go.Scatter(
x=[2, 4],
y=[4, 8],
mode="lines",
line=go.scatter.Line(color="gray"),
showlegend=False)
)
fig.show()
7.5
6.5
sepal_length
5.5
https://plot.ly/python/creating-and-updating-figures/ 13/43
2020/2/6 Creating and Updating Figures | Python | Plotly
4 3
3.5 2.5
3 2
2.5
1.5
2
1
This also works for gures created by Plotly Express using the facet_row and or facet_col
arguments.
https://plot.ly/python/creating-and-updating-figures/ 14/43
2020/2/6 Creating and Updating Figures | Python | Plotly
import plotly.express as px
df = px.data.iris()
fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species",
facet_col="species")
reference_line = go.Scatter(x=[2, 4],
y=[4, 8],
mode="lines",
line=go.scatter.Line(color="gray"),
showlegend=False)
fig.add_trace(reference_line, row=1, col=1)
fig.add_trace(reference_line, row=1, col=2)
fig.add_trace(reference_line, row=1, col=3)
fig.show()
species=setosa species=versicolor
7.5
6.5
sepal_length
5.5
https://plot.ly/python/creating-and-updating-figures/ 15/43
2020/2/6 Creating and Updating Figures | Python | Plotly
4 3
3.5 2.5
3 2
2.5
1.5
2
1
https://plot.ly/python/creating-and-updating-figures/ 16/43
2020/2/6 Creating and Updating Figures | Python | Plotly
For example, specifying the gure title in the gure constructor without magic underscore
notation requires setting the layout argument to dict(title=dict(text="A Chart")).
Similarly, setting the line color of a scatter trace requires setting the marker property to
dict(color="crimson").
https://plot.ly/python/creating-and-updating-figures/ 17/43
2020/2/6 Creating and Updating Figures | Python | Plotly
import plotly.graph_objects as go
fig = go.Figure(
data=[go.Scatter(y=[1, 3, 2], line=dict(color="crimson"))],
layout=dict(title=dict(text="A Chart"))
)
fig.show()
A Chart
2.5
With magic underscore notation, you can accomplish the same thing by passing the gure
constructor a keyword argument named layout_title_text, and by passing the
go.Scatter constructor a keyword argument named line_color.
https://plot.ly/python/creating-and-updating-figures/ 18/43
2020/2/6 Creating and Updating Figures | Python | Plotly
import plotly.graph_objects as go
fig = go.Figure(
data=[go.Scatter(y=[1, 3, 2], line_color="crimson")],
layout_title_text="A Chart"
)
fig.show()
A Chart
2.5
https://plot.ly/python/creating-and-updating-figures/ 19/43
2020/2/6 Creating and Updating Figures | Python | Plotly
Magic underscore notation is supported throughout the graph objects API, and it can often
signi cantly simplify operations involving deeply nested properties.
Note: When you see keyword arguments with underscores passed to a graph
object constructor or method, it is almost always safe to assume that it is an
application of magic underscore notation. We have to say "almost always" rather
than "always" because there are a few property names in the plotly schema that
contain underscores: error_x, error_y, error_z, copy_xstyle, copy_ystyle,
copy_zstyle, paper_bgcolor, and plot_bgcolor. These were added back in the early
days of the library (2012-2013) before we standardized on banning underscores
from property names.
https://plot.ly/python/creating-and-updating-figures/ 20/43
2020/2/6 Creating and Updating Figures | Python | Plotly
import plotly.graph_objects as go
fig = go.Figure(data=go.Bar(x=[1, 2, 3], y=[1, 3, 2]))
fig.update_layout(title_text="A Bar Chart",
title_font_size=30)
fig.show()
A Bar Chart
2.5
1.5
https://plot.ly/python/creating-and-updating-figures/ 21/43
2020/2/6 Creating and Updating Figures | Python | Plotly
fig.update_layout(
title=go.layout.Title(text="A Bar Chart",
font=go.layout.title.Font(size=30)));
https://plot.ly/python/creating-and-updating-figures/ 22/43
2020/2/6 Creating and Updating Figures | Python | Plotly
fig.add_bar(y=[2, 1, 3],
marker=dict(color="MediumPurple"),
name="b", row=1, col=1)
fig.add_bar(y=[1, 3, 2],
marker=dict(color="LightSeaGreen"),
name="d", row=1, col=2)
fig.show()
https://plot.ly/python/creating-and-updating-figures/ 23/43
2020/2/6 Creating and Updating Figures | Python | Plotly
4 4
3.5 3.5
3 3
2.5 2.5
2 2
1.5 1.5
Note that both scatter and bar traces have a marker.color property to control their
coloring. Here is an example of using update_traces to modify the color of all traces.
https://plot.ly/python/creating-and-updating-figures/ 24/43
2020/2/6 Creating and Updating Figures | Python | Plotly
fig.add_bar(y=[2, 1, 3],
marker=dict(color="MediumPurple"),
name="b", row=1, col=1)
fig.add_bar(y=[1, 3, 2],
marker=dict(color="LightSeaGreen"),
name="d", row=1, col=2)
fig.update_traces(marker=dict(color="RoyalBlue"))
fig.show()
https://plot.ly/python/creating-and-updating-figures/ 25/43
2020/2/6 Creating and Updating Figures | Python | Plotly
4 4
3.5 3.5
3 3
2.5 2.5
2 2
1.5 1.5
The update_traces method supports a selector argument to control which traces should
be updated. Only traces with properties that match the selector will be updated. Here is an
example of using a selector to only update the color of the bar traces
https://plot.ly/python/creating-and-updating-figures/ 26/43
2020/2/6 Creating and Updating Figures | Python | Plotly
fig.add_bar(y=[2, 1, 3],
marker=dict(color="MediumPurple"),
name="b", row=1, col=1)
fig.add_bar(y=[1, 3, 2],
marker=dict(color="LightSeaGreen"),
name="d", row=1, col=2)
fig.update_traces(marker=dict(color="RoyalBlue"),
selector=dict(type="bar"))
fig.show()
https://plot.ly/python/creating-and-updating-figures/ 27/43
2020/2/6 Creating and Updating Figures | Python | Plotly
4 4
3.5 3.5
3 3
2.5 2.5
2 2
1.5 1.5
Magic underscore notation can be used in the selector to match nested properties. Here is an
example of updating the color of all traces that were formally colored "MediumPurple".
https://plot.ly/python/creating-and-updating-figures/ 28/43
2020/2/6 Creating and Updating Figures | Python | Plotly
fig.add_bar(y=[2, 1, 3],
marker=dict(color="MediumPurple"),
name="b", row=1, col=1)
fig.add_bar(y=[1, 3, 2],
marker=dict(color="LightSeaGreen"),
name="d", row=1, col=2)
fig.update_traces(marker_color="RoyalBlue",
selector=dict(marker_color="MediumPurple"))
fig.show()
https://plot.ly/python/creating-and-updating-figures/ 29/43
2020/2/6 Creating and Updating Figures | Python | Plotly
4 4
3.5 3.5
3 3
2.5 2.5
2 2
1.5 1.5
For gures with subplots, the update_traces method also supports row and col arguments
to control which traces should be updated. Only traces in the speci ed subplot row and
column will be updated. Here is an example of updating the color of all traces in the second
subplot column
https://plot.ly/python/creating-and-updating-figures/ 30/43
2020/2/6 Creating and Updating Figures | Python | Plotly
fig.add_bar(y=[2, 1, 3],
marker=dict(color="MediumPurple"),
name="b", row=1, col=1)
fig.add_bar(y=[1, 3, 2],
marker=dict(color="LightSeaGreen"),
name="d", row=1, col=2)
fig.update_traces(marker=dict(color="RoyalBlue"),
col=2)
fig.show()
https://plot.ly/python/creating-and-updating-figures/ 31/43
2020/2/6 Creating and Updating Figures | Python | Plotly
4 4
3.5 3.5
3 3
2.5 2.5
2 2
1.5 1.5
The update_traces method can also be used on gures produced by gure factories or
Plotly Express. Here's an example of updating the regression lines produced by Plotly Express
to be dotted.
https://plot.ly/python/creating-and-updating-figures/ 32/43
2020/2/6 Creating and Updating Figures | Python | Plotly
import pandas as pd
import plotly.express as px
df = px.data.iris()
fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species",
facet_col="species", trendline="ols")
fig.update_traces(
line=dict(dash="dot", width=4),
selector=dict(type="scatter", mode="lines"))
fig.show()
species=setosa species=versicolor
8
7.5
6.5
sepal_length
5.5
https://plot.ly/python/creating-and-updating-figures/ 33/43
2020/2/6 Creating and Updating Figures | Python | Plotly
In the example below, the red color of markers is overwritten when updating marker in
update_traces with overwrite=True. Note that setting instead marker_opacity with the
magic underscore would not overwrite marker_color because properties would be
overwritten starting only at the level of marker.opacity.
https://plot.ly/python/creating-and-updating-figures/ 34/43
2020/2/6 Creating and Updating Figures | Python | Plotly
import plotly.graph_objects as go
fig = go.Figure(go.Bar(x=[1, 2, 3], y=[6, 4, 9],
marker_color="red")) # will be overwritten below
fig.update_traces(
overwrite=True,
marker={"opacity": 0.4}
)
fig.show()
https://plot.ly/python/creating-and-updating-figures/ 35/43
2020/2/6 Creating and Updating Figures | Python | Plotly
As its rst argument, the for_each_trace method accepts a function that accepts and
updates one trace at a time. Like update_traces, for_each_trace also accepts selector,
row, and col arguments to control which traces should be considered.
Here is an example of using for_each_trace to replace the equal-sign with a colon in the
legend name of each trace in a gure produced by Plotly Express.
https://plot.ly/python/creating-and-updating-figures/ 36/43
2020/2/6 Creating and Updating Figures | Python | Plotly
import pandas as pd
import plotly.express as px
df = px.data.iris()
fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species")
fig.for_each_trace(
lambda trace: trace.update(name=trace.name.replace("=", ": ")),
)
fig.show()
7.5
6.5
sepal_length
5.5
https://plot.ly/python/creating-and-updating-figures/ 37/43
2020/2/6 Creating and Updating Figures | Python | Plotly
import pandas as pd
import plotly.express as px
df = px.data.iris()
fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species",
facet_col="species")
fig.update_xaxes(showgrid=False)
fig.show()
species=setosa species=versicolor
8
7.5
6.5
sepal_length
5.5
https://plot.ly/python/creating-and-updating-figures/ 38/43
2020/2/6 Creating and Updating Figures | Python | Plotly
There are also for_each_xaxis and for_each_yaxis methods that are analogous to the
for_each_trace method described above. For non-cartesian subplot types (e.g. polar), there
are additional update_{type} and for_each_{type} methods (e.g. update_polar,
for_each_polar).
Here is an example of a chained expression that creates a faceted scatter plot with OLS trend
lines using Plotly Express, sets the title font size using update_layout, disables vertical grid
lines using update_xaxes, updates the width and dash pattern of the trend lines using
update_traces, and then displays the gure using show.
https://plot.ly/python/creating-and-updating-figures/ 39/43
2020/2/6 Creating and Updating Figures | Python | Plotly
import plotly.express as px
df = px.data.iris()
(px.scatter(df, x="sepal_width", y="sepal_length", color="species",
facet_col="species", trendline="ols", title="Iris Dataset")
.update_layout(title_font_size=24)
.update_xaxes(showgrid=False)
.update_traces(
line=dict(dash="dot", width=4),
selector=dict(type="scatter", mode="lines"))
).show()
Iris Dataset
species=setosa species=versicolor
8
7.5
6.5
sepal_length
5.5
Property assignment
Trace and layout properties can be updated using property assignment syntax. Here is an
example of setting the gure title using property assignment
https://plot.ly/python/creating-and-updating-figures/ 40/43
2020/2/6 Creating and Updating Figures | Python | Plotly
example of setting the gure title using property assignment.
import plotly.graph_objects as go
fig = go.Figure(data=go.Bar(x=[1, 2, 3], y=[1, 3, 2]))
fig.layout.title.text = "A Bar Chart"
fig.show()
A Bar Chart
2.5
1.5
And here is an example of updating the bar outline using property assignment
https://plot.ly/python/creating-and-updating-figures/ 41/43
2020/2/6 Creating and Updating Figures | Python | Plotly
import plotly.graph_objects as go
fig = go.Figure(data=go.Bar(x=[1, 2, 3], y=[1, 3, 2]))
fig.data[0].marker.line.width = 4
fig.data[0].marker.line.color = "black"
fig.show()
2.5
1.5
https://plot.ly/python/creating-and-updating-figures/ 42/43
2020/2/6 Creating and Updating Figures | Python | Plotly
Subscribe
Copyright © 2020 Plotly. All rights reserved. Terms of Service Privacy Policy
https://plot.ly/python/creating-and-updating-figures/ 43/43