介绍
2020年7月,Plotly 4.8.2以来的信息被完全重写。
介绍Plotly(Python可用的库)的基本用法,尤其是如何创建经常使用的折线图(散点图)。使用Plotly,您可以创建可以移动的图形,如下图所示。
尽管本文未涉及,但Plotly可以绘制折线图之外的多种图形。还有Plotly的高级API(称为Plotly Express)和使用Plotly的Web应用程序框架(称为Dash)(示例)。
- Reiwa时代的事实标准Python绘图库Plotly Express的基本绘图方法摘要
- 可视化工具仪表板教程-第1部分:安装图-
安装
使用
资料准备
最后,准备正弦曲线和随机序列。
1 2 3 4 | import numpy as np xs = np.linspace(0, 10, 100) sins = np.sin(xs) randoms = np.random.rand(100) |
创建折线图
只需将散点图(
1 2 3 4 5 6 | import plotly.graph_objects as go fig = go.Figure(data=[ go.Scatter(x=xs, y=sins, name="sin"), go.Scatter(x=xs, y=randoms, name="random"), ]) fig.show() |
您可以如上所述用
系列,也可以暂时创建
1 2 3 4 5 | import plotly.graph_objects as go fig = go.Figure() fig.add_trace(go.Scatter(x=xs, y=sins, name="sin")) fig.add_trace(go.Scatter(x=xs, y=randoms, name="random")) fig.show() # 上と同じ結果 |
单击此处以获取图形上的简单操作方法
- 拖动图形以在X轴方向,Y轴方向,矩形上放大
- 在X和Y轴上拖动以在轴向上移动
- 在X和Y轴的末端拖动以在轴向上放大和缩小
- 双击以返回初始显示
图定制
整体图,每个轴设置
让我们通过调用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | fig.update_xaxes(title="x") # X軸タイトルを指定 fig.update_yaxes(title="y") # Y軸タイトルを指定 fig.update_xaxes(range=(1,3)) # X軸の最大最小値を指定 fig.update_xaxes(rangeslider={"visible":True}) # X軸に range slider を表示(下図参照) fig.update_yaxes(scaleanchor="x", scaleratio=1) # Y軸のスケールをX軸と同じに(plt.axis("equal")) fig.update_layout(title="Title") # グラフタイトルを設定 fig.update_layout(font={"family":"Meiryo", "size":20}) # フォントファミリとフォントサイズを指定 fig.update_layout(showlegend=True) # 凡例を強制的に表示(デフォルトでは複数系列あると表示) fig.update_layout(xaxis_type="linear", yaxis_type="log") # X軸はリニアスケール、Y軸はログスケールに fig.update_layout(width=800, height=600) # 図の高さを幅を指定 fig.update_layout(template="plotly_white") # 白背景のテーマに変更 |
主题可以从以下选择。单击此处以获取主题列表
1 2 3 | ['ggplot2', 'seaborn', 'simple_white', 'plotly', 'plotly_white', 'plotly_dark', 'presentation', 'xgridoff', 'ygridoff', 'gridon', 'none'] |
系列设置
如果为
系列选项
1 2 3 4 5 6 | import plotly.graph_objects as go fig = go.Figure() fig.add_trace(go.Scatter(x=xs, y=sins, name="lines", mode="lines")) # 線だけ fig.add_trace(go.Scatter(x=xs, y=sins + 1, name="markers", mode="markers")) # マーカだけ fig.add_trace(go.Scatter(x=xs, y=sins + 2, name="lines+markers", mode="lines+markers")) # 線とマーカ fig.show() |
第二个Y轴
在启用
1 2 3 4 5 6 7 8 9 | import plotly.graph_objects as go from plotly.subplots import make_subplots fig = make_subplots(specs=[[{"secondary_y": True}]]) fig.add_trace(go.Scatter(x=xs, y=sins, name="sin"), secondary_y=False) fig.add_trace(go.Scatter(x=xs, y=randoms, name="random"), secondary_y=True) fig.update_yaxes(title_text="y1", secondary_y=False) fig.update_yaxes(title_text="y2", secondary_y=True) fig.show() |
多个plot
如果用指定
1 2 3 4 5 6 7 | import plotly.graph_objects as go from plotly.subplots import make_subplots fig = make_subplots(rows=1, cols=2) fig.add_trace(go.Scatter(x=xs, y=sins, name="sin"), row=1, col=1) fig.add_trace(go.Scatter(x=xs, y=randoms, name="random"), row=1, col=2) fig.show() |
其他
1 2 | fig.write_html("a.html") # 単独HTMLファイルにぐりぐりできる状態で出力 fig.write_image("a.png") # 画像に出力(グラフ上のアイコンの"download as a png"でもOK) |