安装
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple plotly==4.5.2
用conda install指令无法装成,即使换了清华源也没用
相关链接
主页
API列表
示例
官方提供了一个在线编辑工具,可以生成图形:web editor
plotly可视化库主打可交互、开源、基于web
许可:MIT Licensed
图形对象
1、创建一个Figure对象
Figure(data=None, layout=None, frames=None, skip_invalid=False, **kwargs)
data为图形的底层数据,见trace type列表(plotly定义的一系列数据结构)
layout定义布局属性,如title、font、width、height、colorscale、legend,属性很多,说明见class plotly.graph_objs.Layout
2、显示一个Figure
Figure.show(*args, **kwargs)
参数用于设置renderer,如fig.show(renderer="svg")
renderer可以通过以下语句查看
import plotly.io as pio
pio.renderers
Renderers configuration
-----------------------
Default renderer: 'notebook_connected'
Available renderers:
['plotly_mimetype', 'jupyterlab', 'nteract', 'vscode',
'notebook', 'notebook_connected', 'kaggle', 'azure', 'colab',
'cocalc', 'databricks', 'json', 'png', 'jpeg', 'jpg', 'svg',
'pdf', 'browser', 'firefox', 'chrome', 'chromium', 'iframe',
'iframe_connected', 'sphinx_gallery']
示例一:
import plotly.graph_objects as go
fig = go.Figure(
data=[go.Bar(y=[2, 1, 3])],
layout_title_text="A Figure Displayed with fig.show()"
)
fig.show()
示例二:
ig = {
"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.io.show function
import plotly.io as pio
pio.show(fig)
3、特殊图形
生成特殊图形,如gantt图、quiver图
Figure factories,注意其中有一些已经废弃
示例:
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()
4、增加数据
Figure.add_traces(data, rows=None, cols=None, secondary_ys=None)
示例:
import plotly.graph_objects as go
fig = go.Figure()
fig.add_trace(go.Bar(x=[1, 2, 3], y=[1, 3, 2]))
fig.show()
5、画子图
plotly.subplots.make_subplots(rows=1, cols=1, shared_xaxes=False, shared_yaxes=False, start_cell='top-left', print_grid=False, horizontal_spacing=None, vertical_spacing=None, subplot_titles=None, column_widths=None, row_heights=None, specs=None, insets=None, column_titles=None, row_titles=None, x_title=None, y_title=None, **kwargs)
示例:
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()
6、改变已有Figure的属性
Figure.update_traces(patch=None, selector=None, row=None, col=None, secondary_y=None, overwrite=False, **kwargs)
Figure.update_layout(dict1=None, overwrite=False, **kwargs)
示例一:
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()
以下的写法与上面等价:
fig.update_layout(title_text="A Bar Chart",
title_font_size=30)
fig.update_layout(title_text="A Bar Chart",
title_font=dict(size=30))
fig.update_layout(title=dict(text="A Bar Chart"),
font=dict(size=30))
fig.update_layout({"title": {"text": "A Bar Chart",
"font": {"size": 30}}})
fig.update_layout(
title=go.layout.Title(text="A Bar Chart",
font=go.layout.title.Font(size=30)));
示例二:
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)
#改变所有marker的颜色
fig.update_traces(marker=dict(color="RoyalBlue"))
fig.show()
交互元素
Figure对象实现一些交互操作,如鼠标选点、区域选取、缩放、视角旋转、视角拉伸等等,见Configuration in Python
除了figure对象,还可以添加一些控件,实现简单的交互功能Custom Buttons、Dropdown Menus、Sliders、Range Slider and Selector
但是这些控件都只是很有限的扩展,要想更灵活只能编写dash的web应用程序
Custom Buttons
layout.updatemenus.buttons.method,枚举类型,“restyle” | “relayout” | “animate” | “update” | “skip”,method属性决定button的on click行为:
“restyle”: 修改data或data的属性,on click事件里只会修改Figure中的data属性,而不会修改layout属性;
“relayout”: 修改layout属性,同上,on click事件只会修改layout属性,不会修改data属性
“update”: 修改data和layout属性
“animate”: 开始或暂停动画
另外,也可以用JavaScript定义自己的updatemenu events
示例:
import plotly.graph_objects as go
import pandas as pd
# Load dataset
df = pd.read_csv(
"https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv")
df.columns = [col.replace("AAPL.", "") for col in df.columns]
# Initialize figure
fig = go.Figure()
# Add Traces
fig.add_trace(
go.Scatter(x=list(df.index),
y=list(df.High),
name="High",
line=dict(color="#33CFA5")))
fig.add_trace(
go.Scatter(x=list(df.index),
y=[df.High.mean()] * len(df.index),
name="High Average",
visible=False,
line=dict(color="#33CFA5", dash="dash")))
fig.add_trace(
go.Scatter(x=list(df.index),
y=list(df.Low),
name="Low",
line=dict(color="#F06A6A")))
fig.add_trace(
go.Scatter(x=list(df.index),
y=[df.Low.mean()] * len(df.index),
name="Low Average",
visible=False,
line=dict(color="#F06A6A", dash="dash")))
# Add Annotations and Buttons
high_annotations = [dict(x="2016-03-01",
y=df.High.mean(),
xref="x", yref="y",
text="High Average:<br> %.2f" % df.High.mean(),
ax=0, ay=-40),
dict(x=df.High.idxmax(),
y=df.High.max(),
xref="x", yref="y",
text="High Max:<br> %.2f" % df.High.max(),
ax=0, ay=-40)]
low_annotations = [dict(x="2015-05-01",
y=df.Low.mean(),
xref="x", yref="y",
text="Low Average:<br> %.2f" % df.Low.mean(),
ax=-40, ay=40),
dict(x=df.High.idxmin(),
y=df.Low.min(),
xref="x", yref="y",
text="Low Min:<br> %.2f" % df.Low.min(),
ax=0, ay=40)]
fig.update_layout(
updatemenus=[
dict(
type="buttons",
direction="right",
active=0,
x=0.57,
y=1.2,
buttons=list([
dict(label="None",
method="update", #method属性:修改data和layout
args=[{"visible": [True, False, True, False]}, #4组data的visible属性
{"title": "Yahoo", #layout的title属性
"annotations": []}]), #layout的annotations属性
dict(label="High",
method="update",
args=[{"visible": [True, True, False, False]},
{"title": "Yahoo High",
"annotations": high_annotations}]),
dict(label="Low",
method="update",
args=[{"visible": [False, False, True, True]},
{"title": "Yahoo Low",
"annotations": low_annotations}]),
dict(label="Both",
method="update",
args=[{"visible": [True, True, True, True]},
{"title": "Yahoo",
"annotations": high_annotations + low_annotations}]),
]),
)
])
# Set title
fig.update_layout(
title_text="Yahoo",
xaxis_domain=[0.05, 1.0]
)
fig.show()
错误示例:
想实现z轴反转的功能,但是method属性设置了restyle导致没有效果
import plotly.graph_objects as go
import pandas as pd
# Read data from a csv
z_data = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/api_docs/mt_bruno_elevation.csv')
fig = go.Figure(data=[go.Surface(z=z_data.values,colorscale='Cividis')])
fig.update_traces(contours_z=dict(show=True, usecolormap=True,
highlightcolor="limegreen", project_z=True))
fig.update_layout(
updatemenus=[
dict(
buttons=list([
dict(
args=[{"scene.zaxis.autorange" : True}],
label="False",
method="restyle" #此处应改为relayout
),
dict(
args=[{"scene.zaxis.autorange" : "reversed"} ],
label="True",
method="restyle" #此处应改为relayout
)
]),
direction="down",
pad={"r": 10, "t": 10},
showactive=True,
x=0.38,
xanchor="left",
y=button_layer_1_height,
yanchor="top"
)
]
)
fig.update_layout(title='Mt Bruno Elevation', autosize=False,
scene_camera_eye=dict(x=1.87, y=0.88, z=-0.64),
width=900, height=900,
margin=dict(l=65, r=50, b=65, t=90),
annotations=[
dict(text="Reverse<br>ZAxis", x=0.3, xref="paper", y=1.07,
yref="paper", showarrow=False)
]
)
fig.show()
主题
plotly内置了一系列的主题可以选择
Theming and templates