[英]Python Plotly: Adding a horizontal line to a scatter plot that has multiple subplots
[英]how to add horizontal line in all subplots in plotly python
我想在我生成的每个子图中在0.09 and -0.09
处添加水平线。 以下是我的代码来做到这一点。
trace1 = go.Scatter(
x=df1['transaction_date'],
y=df1['difference'],
)
trace2 = go.Scatter(
x=df2['transaction_date'],
y=df2['difference'],
)
trace3 = go.Scatter(
x=df3['transaction_date'],
y=df3['difference'],
)
trace4 = go.Scatter(
x=df4['transaction_date'],
y=df4['difference'],
)
fig = tools.make_subplots(rows=2, cols=2,subplot_titles=('DF1 HS', DF2 HSD',
'DF3 HD', 'DF4 SD',
))
fig.append_trace(trace1, 1, 1)
fig.append_trace(trace2, 1, 2)
fig.append_trace(trace3, 2, 1)
fig.append_trace(trace4, 2, 2)
然后我想将这 4 个子图保存为磁盘上的jpeg
。 我怎么能在python中做到这一点
尝试使用以下shapes
更新fig
对象的layout
:
import plotly.graph_objs as go
from plotly import tools
from plotly.offline import init_notebook_mode, plot
df = pd.DataFrame(np.random.randint(0,100,size=(20,2)),
index=pd.date_range(start='2018-08-21',end='2018-09-09'),
columns=['A','B'])
trace1 = go.Scatter(x=df.index,y=df['A'],)
trace2 = go.Scatter(x=df.index,y=df['B'],)
fig = tools.make_subplots(rows=2, cols=1,subplot_titles=(['A','B']))
fig.append_trace(trace1, 1, 1)
fig.append_trace(trace2, 2, 1)
fig['layout'].update(shapes=[{'type': 'line','y0':50,'y1': 50,'x0':str(df.index[0]),
'x1':str(df.index[-1]),'xref':'x1','yref':'y1',
'line': {'color': 'red','width': 2.5}},
{'type': 'line','y0':50,'y1': 50,'x0':str(df.index[0]),
'x1':str(df.index[-1]),'xref':'x2','yref':'y2',
'line': {'color': 'red','width': 2.5}}])
plot(fig,show_link=False,image='jpeg',image_filename='Temp_plot')
该图将保存为Temp_plot.jpeg
。 检查下面的图像。
这种方法的缺点是我们需要仔细为子图的xref
和yref
提供轴值。
matplotlib
解决方案没问题:数据:
dict = {
"a":np.random.randint(low=-10,high=10,size=20),
"b":np.random.randint(low=-10,high=10,size=20),
"c":np.random.randint(low=-10,high=10,size=20),
"d":np.random.randint(low=-10,high=10,size=20),
}
df = pd.DataFrame(dict)
阴谋:
fig, axes = plt.subplots(2,2, figsize=(20,10), sharex=True, sharey=True)
for i,j in zip(axes.ravel(), list(df)):
i.plot(df.index, df[j], 'ro')
i.hlines(y=-3, xmin=0, xmax=22)
i.hlines(y=3, xmin=0, xmax=22)
fig.savefig("testplot.png")
结果:
我对 Plotly 还很陌生,所以也许 API 刚刚更新,但根据此处的文档,似乎有一个更简单的解决方案。 只需要使用fig.add_hline()
语法,同时指定应该在哪个子图(col 和 row)上绘制,如下所示:
fig.add_hline(y=1, line_dash="dot", row=1, col=1, line_color="#000000", line_width=2)
该行将指示 Plotly 在位于row = 1
的子图中绘制一条水平线y = 1
row = 1
; col = 1
。
或者,如 dox 中所述,“all”关键字可以作为row
或col
参数的值传递,以指示 plotly 在(等待它...)所有子图上绘制线!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.