Fundamentals | Python | Plotly
as below.
The Figure Data Structure | Python | Plotly
Express, plotly推荐的高级的API;
plotly.graph_objects.Figure的结果,实际上就是一个json的对象。
import plotly.express as px
fig = px.line(x=["a","b","c"], y=[1,3,2], title="sample figure")
print(fig)
fig.show()
Figure({
'data': [{'hovertemplate': 'x=%{x}<br>y=%{y}<extra></extra>',
'legendgroup': '',
'line': {'color': '#636efa', 'dash': 'solid'},
'marker': {'symbol': 'circle'},
'mode': 'lines',
'name': '',
'orientation': 'v',
'showlegend': False,
'type': 'scatter',
'x': array(['a', 'b', 'c'], dtype=object),
'xaxis': 'x',
'y': array([1, 3, 2]),
'yaxis': 'y'}],
'layout': {'legend': {'tracegroupgap': 0},
'template': '...',
'title': {'text': 'sample figure'},
'xaxis': {'anchor': 'y', 'domain': [0.0, 1.0], 'title': {'text': 'x'}},
'yaxis': {'anchor': 'x', 'domain': [0.0, 1.0], 'title': {'text': 'y'}}}
})
Plotly.js 支持(严格定义好模式)格式化的输入。图形表示为具有称为“属性”的命名节点的树。树的根节点具有三个顶级属性:data,layout 和 frames, 数据、布局和框架。
访问属性可以直接用.操作符,例如,layout.width; 数据可以用 layout.annotations[].text。
操作 plotly.graph_objects.Figure 对象时,可以直接使用 Python 对象属性设置属性,例如fig.layout.title.font.family=“Open Sans” 或使用更新方法和“魔法下划线”,例如fig.update_layout(title_font_family=“Open Sans”)
Data
The first of the three top-level attributes of a figure is data
, whose value must be a list of dicts referred to as “traces”.
trace-轨迹,data包含很多的个trace, 可以有不同的类型。
layout
he second of the three top-level attributes of a figure is layout
, whose value is referred to in text as “the layout” and must be a dict, containing attributes that control positioning and configuration of non-data-related parts of the figure such as:
layout-布局,用来控制位置以及除了数据之外的相关配置。
- Dimensions and margins, which define the bounds of “paper coordinates” (see below)
- Figure-wide defaults: templates, fonts, colors, hover-label and modebar defaults
- Title and legend (positionable in container and/or paper coordinates)
- Color axes and associated color bars (positionable in paper coordinates)
- Subplots of various types on which can be drawn multiple traces and which are positioned in paper coordinates:
xaxis
,yaxis
,xaxis2
,yaxis3
etc: X and Y cartesian axes, the intersections of which are cartesian subplotsscene
,scene2
,scene3
etc: 3d scene subplotsternary
,ternary2
,ternary3
,polar
,polar2
,polar3
,geo
,geo2
,geo3
,mapbox
,mapbox2
,mabox3
etc: ternary, polar, geo or mapbox subplots
- Non-data marks which can be positioned in paper coordinates, or in data coordinates linked to 2d cartesian subplots:
- Controls which can be positioned in paper coordinates and which can trigger Plotly.js functions when interacted with by a user:
updatemenus
: single buttons, toggles and dropdown menussliders
: slider controls
frame
The third of the three top-level attributes of a figure is frames
, whose value must be a list of dicts that define sequential frames in an animated plot. Each frame contains its own data attribute as well as other parameters. Animations are usually triggered and controlled via controls defined in layout.sliders and/or layout.updatemenus。
frame-帧,用来定义动画过程的东西。静态的用不到。
Creating and Updating Figures | Python | Plotly
Figures As Dictionaries - 最低等的API
fig = dict({
"data": [{"type": "bar",
"x": [1, 2, 3],
"y": [1, 3, 2]}],
"layout": {"title": {"text": "A Figure Specified By Python Dictionary"}}
})
# To display the figure defined by this dict, use the low-level plotly.io.show function
import plotly.io as pio
pio.show(fig)
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-HCLnQZt8-1633864207869)(Plotly.assets/image-20211010175518944.png)]
Figures as Graph Objects
Graph Objects | Python | Plotly
Graph Objects Compared to Dictionaries
Graph objects have several benefits compared to plain Python dictionaries:
- Graph objects provide precise data validation. If you provide an invalid property name or an invalid property value as the key to a graph object, an exception will be raised with a helpful error message describing the problem. This is not the case if you use plain Python dictionaries and lists to build your figures.
- Graph objects contain descriptions of each valid property as Python docstrings, with a full API reference available. You can use these docstrings in the development environment of your choice to learn about the available properties as an alternative to consulting the online Full Reference.
- Properties of graph objects can be accessed using both dictionary-style key lookup (e.g.
fig["layout"]
) or class-style property access (e.g.fig.layout
). - Graph objects support higher-level convenience functions for making updates to already constructed figures (
.update_layout()
,.add_trace()
etc). - Graph object constructors and update methods accept “magic underscores” (e.g.
go.Figure(layout_title_text="The Title")
rather thandict(layout=dict(title=dict(text="The Title")))
) for more compact code. - Graph objects support attached rendering (
.show()
) and exporting functions (.write_image()
) that automatically invoke the appropriate functions from theplotly.io
module.
When to use Graph Objects vs Plotly Express
The recommended way to create figures is using the functions in the plotly.express module, collectively known as Plotly Express, which all return instances of plotly.graph_objects.Figure
, so every figure produced with the plotly
library actually uses graph objects under the hood, unless manually constructed out of dictionaries.
That said, certain kinds of figures are not yet possible to create with Plotly Express, such as figures that use certain 3D trace-types like mesh
or isosurface
. In addition, certain figures are cumbersome to create by starting from a figure created with Plotly Express, for example figures with subplots of different types, dual-axis plots, or faceted plots with multiple different types of traces. To construct such figures, it can be easier to start from an empty plotly.graph_objects.Figure
object (or one configured with subplots via the make_subplots() function) and progressively add traces and update attributes as above. Every plotly
documentation page lists the Plotly Express option at the top if a Plotly Express function exists to make the kind of chart in question, and then the graph objects version below.
Note that the figures produced by Plotly Express in a single function-call are easy to customize at creation-time, and to manipulate after creation using the update_*
and add_*
methods.
import pandas as pd
df = pd.DataFrame({
"Fruit": ["Apples", "Oranges", "Bananas", "Apples", "Oranges", "Bananas"],
"Contestant": ["Alex", "Alex", "Alex", "Jordan", "Jordan", "Jordan"],
"Number Eaten": [2, 1, 3, 1, 3, 2],
})
# Plotly Express
import plotly.express as px
fig = px.bar(df, x="Fruit", y="Number Eaten", color="Contestant", barmode="group")
fig.show()
# Graph Objects
import plotly.graph_objects as go
fig = go.Figure()
for contestant, group in df.groupby("Contestant"):
fig.add_trace(go.Bar(x=group["Fruit"], y=group["Number Eaten"], name=contestant,
hovertemplate="Contestant=%s<br>Fruit=%%{x}<br>Number Eaten=%%{y}<extra></extra>"% contestant))
fig.update_layout(legend_title_text = "Contestant")
fig.update_xaxes(title_text="Fruit")
fig.update_yaxes(title_text="Number Eaten")
fig.show()
Plotly Express
最高端的API
import plotly.express as px
df = px.data.iris()
fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species", title="A Plotly Express Figure")
# If you print the figure, you'll see that it's just a regular figure with data and layout
# print(fig)
fig.show()
Figure Factories
Figure factories (included in plotly.py
in the plotly.figure_factory
module) are functions that produce graph object figures, often to satisfy the needs of specialized domains. Here’s an example of using the create_quiver()
figure factory to construct a graph object figure 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
fig = ff.create_quiver(x1, y1, u1, v1)
fig.show()
Make Subplots
创建子图
The plotly.subplots.make_subplots()
function produces a graph object figure that is preconfigured with a grid of subplots that traces can be added to. The add_trace()
function will be discussed more below.
from plotly.subplots import make_subplots
fig = make_subplots(rows=1, cols=2)
fig.add_trace(go.Scatter(y=[4, 2, 1], mode="lines"), row=1, col=1)
fig.add_trace(go.Bar(y=[2, 1, 3]), row=1, col=2)
fig.show()
Updating Figures
Regardless of how a graph object figure was constructed, it can be updated by adding additional traces to it and modifying its properties.
Adding Traces
New traces can be added to a graph object figure 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 figure. This allows you to start with an empty figure, and add traces to it sequentially. The append_trace()
method does the same thing, although it does not return the figure.
import plotly.graph_objects as go
fig = go.Figure()
fig.add_trace(go.Bar(x=[1, 2, 3], y=[1, 3, 2]))
fig.show()
You can also add traces to a figure produced by a figure factory or Plotly Express.
import plotly.express as px
df = px.data.iris()
fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species",
title="Using The add_trace() method With A Plotly Express Figure")
fig.add_trace(
go.Scatter(
x=[2, 4],
y=[4, 8],
mode="lines",
line=go.scatter.Line(color="gray"),
showlegend=False)
)
fig.show()
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-gIYzF8qv-1633864207872)(Plotly.assets/image-20211010180836526.png)]
Adding Traces To Subplots
If a figure was created using plotly.subplots.make_subplots()
, then supplying the row
and col
arguments to add_trace()
can be used to add a trace to a particular subplot.
from plotly.subplots import make_subplots
fig = make_subplots(rows=1, cols=2)
fig.add_trace(go.Scatter(y=[4, 2, 1], mode="lines"), row=1, col=1)
fig.add_trace(go.Bar(y=[2, 1, 3]), row=1, col=2)
fig.show()
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-QQKbyTT5-1633864207874)(Plotly.assets/image-20211010180905150.png)]
This also works for figures created by Plotly Express using the facet_row
and or facet_col
arguments.
import plotly.express as px
df = px.data.iris()
fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species", facet_col="species",
title="Adding Traces To Subplots Witin A Plotly Express Figure")
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()
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-rRXrgTw0-1633864207878)(Plotly.assets/image-20211010180959788.png)]
Add Trace Convenience Methods
As an alternative to the add_trace()
method, graph object figures have a family of methods of the form add_{trace}
(where {trace}
is the name of a trace type) for constructing and adding traces of each trace type.
Here is the previous subplot example, adapted to add the scatter trace using fig.add_scatter()
and to add the bar trace using fig.add_bar()
.
from plotly.subplots import make_subplots
fig = make_subplots(rows=1, cols=2)
fig.add_scatter(y=[4, 2, 1], mode="lines", row=1, col=1)
fig.add_bar(y=[2, 1, 3], row=1, col=2)
fig.show()
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-7PfwRkAT-1633864207880)(Plotly.assets/image-20211010181159902.png)]
Magic Underscore Notation
To make it easier to work with nested properties, graph object constructors and many graph object methods support magic underscore notation.
This allows you to reference nested properties by joining together multiple nested property names with underscores.
For example, specifying the figure title in the figure 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")
.
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 Graph Objects Figure Without Magic Underscore Notation"))
)
fig.show()
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-C8tq8SiD-1633864207888)(Plotly.assets/image-20211010181324285.png)]
With magic underscore notation, you can accomplish the same thing by passing the figure constructor a keyword argument named layout_title_text
, and by passing the go.Scatter
constructor a keyword argument named line_color
.
下划线这么用还是方便不少的。
import plotly.graph_objects as go
fig = go.Figure(
data=[go.Scatter(y=[1, 3, 2], line_color="crimson")],
layout_title_text="A Graph Objects Figure With Magic Underscore Notation"
)
fig.show()
Updating Figure Layouts
Graph object figures support an update_layout()
method that may be used to update multiple nested properties of a figure’s layout.
Here is an example of updating the text and font size of a figure’s title using update_layout()
.
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="Using update_layout() With Graph Object Figures",
title_font_size=30)
fig.show()
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-BCVgttC2-1633864207891)(Plotly.assets/image-20211010181949756.png)]
Updating Traces
Graph object figures support an update_traces()
method that may be used to update multiple nested properties of one or more of a figure’s traces.
To show some examples, we will start with a figure that contains bar
and scatter
traces across two subplots.
from plotly.subplots import make_subplots
fig = make_subplots(rows=1, cols=2)
fig.add_scatter(y=[4, 2, 3.5], mode="markers",
marker=dict(size=20, color="LightSeaGreen"),
name="a", row=1, col=1)
fig.add_bar(y=[2, 1, 3],
marker=dict(color="MediumPurple"),
name="b", row=1, col=1)
fig.add_scatter(y=[2, 3.5, 4], mode="markers",
marker=dict(size=20, color="MediumPurple"),
name="c", row=1, col=2)
fig.add_bar(y=[1, 3, 2],
marker=dict(color="LightSeaGreen"),
name="d", row=1, col=2)
fig.show()
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-hacmfzxN-1633864207892)(Plotly.assets/image-20211010182055074.png)]
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.
from plotly.subplots import make_subplots
fig = make_subplots(rows=1, cols=2)
fig.add_scatter(y=[4, 2, 3.5], mode="markers",
marker=dict(size=20, color="LightSeaGreen"),
name="a", row=1, col=1)
fig.add_bar(y=[2, 1, 3],
marker=dict(color="MediumPurple"),
name="b", row=1, col=1)
fig.add_scatter(y=[2, 3.5, 4], mode="markers",
marker=dict(size=20, color="MediumPurple"),
name="c", row=1, col=2)
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()
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-xu6meHwL-1633864207893)(Plotly.assets/image-20211010182218400.png)]
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.
from plotly.subplots import make_subplots
fig = make_subplots(rows=1, cols=2)
fig.add_scatter(y=[4, 2, 3.5], mode="markers",
marker=dict(size=20, color="LightSeaGreen"),
name="a", row=1, col=1)
fig.add_bar(y=[2, 1, 3],
marker=dict(color="MediumPurple"),
name="b", row=1, col=1)
fig.add_scatter(y=[2, 3.5, 4], mode="markers",
marker=dict(size=20, color="MediumPurple"),
name="c", row=1, col=2)
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()
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-fPUFcGgJ-1633864207896)(Plotly.assets/image-20211010182258858.png)]
总之,update_traces可以去更新trace的字段,并且可以进行一些筛选,指定某些trace进行更行。
Overwrite Existing Properties When Using Update Methods
update_layout()
and update_traces()
have an overwrite
keyword argument, defaulting to False, in which case updates are applied recursively to the existing nested property structure. When set to True, the prior value of existing properties is overwritten with the provided value.
Conditionally Updating Traces
Suppose the updates that you want to make to a collection of traces depend on the current values of certain trace properties. The update_traces()
method cannot handle this situation, but the for_each_trace()
method can!
As its first 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 convert the only markers for the "setosa"
to square symbols in a Plotly Express Figure.
Note that this is possible because Plotly Express figures are made up of a separate trace for each column in the input data frame
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",
title="Conditionally Updating Traces In A Plotly Express Figure With for_each_trace()")
fig.for_each_trace(
lambda trace: trace.update(marker_symbol="square") if trace.name == "setosa" else (),
)
fig.show()
Updating Figure Axes
Graph object figures support update_xaxes()
and update_yaxes()
methods that may be used to update multiple nested properties of one or more of a figure’s axes. Here is an example of using update_xaxes()
to disable the vertical grid lines across all subplots in a figure produced by Plotly Express.
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", title="Using update_xaxes() With A Plotly Express Figure")
fig.update_xaxes(showgrid=False)
fig.show()
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()
).
Displaying Figures | Python | Plotly
Displaying Figures
Plotly’s Python graphing library, plotly.py
, gives you a wide range of options for how and where to display your figures.
In general, there are five different approaches you can take in order to display plotly
figures:
- Using the
renderers
framework in the context of a script or notebook (the main topic of this page) - Using Dash in a web app context
- Using a
FigureWidget
rather than aFigure
in anipywidgets
context - By exporting to an HTML file and loading that file in a browser immediately or later
- By rendering the figure to a static image file using Kaleido such as PNG, JPEG, SVG, PDF or EPS and loading the resulting file in any viewer
Each of the first three approaches is discussed below.
Plotly Express | Python | Plotly
Overview
The plotly.express
module (usually imported as px
) contains functions that can create entire figures at once, and is referred to as Plotly Express or PX. Plotly Express is a built-in part of the plotly
library, and is the recommended starting point for creating most common figures. Every Plotly Express function uses graph objects internally and returns a plotly.graph_objects.Figure
instance. Throughout the plotly
documentation, you will find the Plotly Express way of building figures at the top of any applicable page, followed by a section on how to use graph objects to build similar figures. Any figure created in a single function call with Plotly Express could be created using graph objects alone, but with between 5 and 100 times more code.
Plotly Express provides more than 30 functions for creating different types of figures. The API for these functions was carefully designed to be as consistent and easy to learn as possible, making it easy to switch from a scatter plot to a bar chart to a histogram to a sunburst chart throughout a data exploration session. Scroll down for a gallery of Plotly Express plots, each made in a single function call.
Plotly Express currently includes the following functions:
- Basics:
scatter
,line
,area
,bar
,funnel
,timeline
- Part-of-Whole:
pie
,sunburst
,treemap
,icicle
,funnel_area
- 1D Distributions:
histogram
,box
,violin
,strip
,ecdf
- 2D Distributions:
density_heatmap
,density_contour
- Matrix or Image Input:
imshow
- 3-Dimensional:
scatter_3d
,line_3d
- Multidimensional:
scatter_matrix
,parallel_coordinates
,parallel_categories
- Tile Maps:
scatter_mapbox
,line_mapbox
,choropleth_mapbox
,density_mapbox
- Outline Maps:
scatter_geo
,line_geo
,choropleth
- Polar Charts:
scatter_polar
,line_polar
,bar_polar
- Ternary Charts:
scatter_ternary
,line_ternary
Subplots | Python | Plotly
Subplots and Plotly Express
subplot是传统的做法; plot express 有兼容的做法,Facet and Trellis Plots,利用分面或是分列。
Simple Subplot
Figures with subplots are created using the make_subplots
function from the plotly.subplots
module.
Here is an example of creating a figure that includes two scatter
traces which are side-by-side since there are 2 columns and 1 row in the subplot layout.
from plotly.subplots import make_subplots
import plotly.graph_objects as go
fig = make_subplots(rows=1, cols=2)
fig.add_trace(
go.Scatter(x=[1, 2, 3], y=[4, 5, 6]),
row=1, col=1
)
fig.add_trace(
go.Scatter(x=[20, 30, 40], y=[50, 60, 70]),
row=1, col=2
)
fig.update_layout(height=600, width=800, title_text="Side By Side Subplots")
fig.show()
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-7JY3Oi0G-1633864207899)(Plotly.assets/image-20211010184620621.png)]
subplot 可以单独设置每一个图的坐标,标题等等
Customizing Subplot Axes
After a figure with subplots is created using the make_subplots
function, its axis properties (title, font, range, grid style, etc.) can be customized using the update_xaxes
and update_yaxes
graph object figure methods. By default, these methods apply to all of the x axes or y axes in the figure. The row
and col
arguments can be used to control which axes are targeted by the update.
Here is an example that creates a figure with a 2 x 2 subplot grid, populates each subplot with a scatter trace, and then updates the x and y axis titles for each subplot individually.
from plotly.subplots import make_subplots
import plotly.graph_objects as go
# Initialize figure with subplots
fig = make_subplots(
rows=2, cols=2, subplot_titles=("Plot 1", "Plot 2", "Plot 3", "Plot 4")
)
# Add traces
fig.add_trace(go.Scatter(x=[1, 2, 3], y=[4, 5, 6]), row=1, col=1)
fig.add_trace(go.Scatter(x=[20, 30, 40], y=[50, 60, 70]), row=1, col=2)
fig.add_trace(go.Scatter(x=[300, 400, 500], y=[600, 700, 800]), row=2, col=1)
fig.add_trace(go.Scatter(x=[4000, 5000, 6000], y=[7000, 8000, 9000]), row=2, col=2)
# Update xaxis properties
fig.update_xaxes(title_text="xaxis 1 title", row=1, col=1)
fig.update_xaxes(title_text="xaxis 2 title", range=[10, 50], row=1, col=2)
fig.update_xaxes(title_text="xaxis 3 title", showgrid=False, row=2, col=1)
fig.update_xaxes(title_text="xaxis 4 title", type="log", row=2, col=2)
# Update yaxis properties
fig.update_yaxes(title_text="yaxis 1 title", row=1, col=1)
fig.update_yaxes(title_text="yaxis 2 title", range=[40, 80], row=1, col=2)
fig.update_yaxes(title_text="yaxis 3 title", showgrid=False, row=2, col=1)
fig.update_yaxes(title_text="yaxis 4 title", row=2, col=2)
# Update title and height
fig.update_layout(title_text="Customizing Subplot Axes", height=700)
fig.show()
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-8wGi5p1X-1633864207900)(Plotly.assets/image-20211010185040368.png)]
## Subplots with Shared X-Axes
常用的,共享x轴
The shared_xaxes
argument to make_subplots
can be used to link the x axes of subplots in the resulting figure. The vertical_spacing
argument is used to control the vertical spacing between rows in the subplot grid.
Here is an example that creates a figure with 3 vertically stacked subplots with linked x axes. A small vertical spacing value is used to reduce the spacing between subplot rows.
from plotly.subplots import make_subplots
import plotly.graph_objects as go
fig = make_subplots(rows=3, cols=1,
shared_xaxes=True,
vertical_spacing=0.02)
fig.add_trace(go.Scatter(x=[0, 1, 2], y=[10, 11, 12]),
row=3, col=1)
fig.add_trace(go.Scatter(x=[2, 3, 4], y=[100, 110, 120]),
row=2, col=1)
fig.add_trace(go.Scatter(x=[3, 4, 5], y=[1000, 1100, 1200]),
row=1, col=1)
fig.update_layout(height=600, width=600,
title_text="Stacked Subplots with Shared X-Axes")
fig.show()
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-377Wb8ev-1633864207901)(Plotly.assets/image-20211010185200260.png)]
Facet and Trellis Plots | Python | Plotly
Facet and Trellis Plots
Facet plots, also known as trellis plots or small multiples, are figures made up of multiple subplots which have the same set of axes, where each subplot shows a subset of the data. While it is straightforward to use plotly
's subplot capabilities to make such figures, it’s far easier to use the built-in facet_row
and facet_col
arguments in the various Plotly Express functions.
Plotly Express is the easy-to-use, high-level interface to Plotly, which operates on a variety of types of data and produces easy-to-style figures.
Scatter Plot Column Facets
import plotly.express as px
df = px.data.tips()
fig = px.scatter(df, x="total_bill", y="tip", color="smoker", facet_col="sex")
fig.show()
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ggj9q5z2-1633864207902)(Plotly.assets/image-20211010190440735.png)]
Bar Chart Row Facets
import plotly.express as px
df = px.data.tips()
fig = px.bar(df, x="size", y="total_bill", color="sex", facet_row="smoker")
fig.show()
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-3ss30Sfq-1633864207903)(Plotly.assets/image-20211010190457543.png)]
Adding Lines and Rectangles to Facet Plots
这个也是有点用处的
introduced in plotly 4.12
It is possible to add labelled horizontal and vertical lines and rectangles to facet plots using .add_hline()
, .add_vline()
, .add_hrect()
or .add_vrect()
. The default row
and col
values are "all"
but this can be overridden, as with the rectangle below, which only appears in the first column.
import plotly.express as px
df = px.data.stocks(indexed=True)
fig = px.line(df, facet_col="company", facet_col_wrap=2)
fig.add_hline(y=1, line_dash="dot",
annotation_text="Jan 1, 2018 baseline",
annotation_position="bottom right")
fig.add_vrect(x0="2018-09-24", x1="2018-12-18", col=1,
annotation_text="decline", annotation_position="top left",
fillcolor="green", opacity=0.25, line_width=0)
fig.show()
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-BUHwqMT8-1633864207904)(Plotly.assets/image-20211010190547296.png)]
Customizing Subplot Figure Titles
Since subplot figure titles are annotations, you can use the for_each_annotation
function to customize them, for example to remove the equal-sign (=
).
In the following example, we pass a lambda function to for_each_annotation
in order to change the figure subplot titles from smoker=No
and smoker=Yes
to just No
and Yes
.
import plotly.express as px
fig = px.scatter(px.data.tips(), x="total_bill", y="tip", facet_col="smoker")
fig.for_each_annotation(lambda a: a.update(text=a.text.split("=")[-1]))
fig.show()
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-acin0xdh-1633864207905)(Plotly.assets/image-20211010190851015.png)]