简体   繁体   English

如何在plotly python的所有子图中添加水平线

[英]how to add horizontal line in all subplots in plotly python

I want to add horizontal line at 0.09 and -0.09 in every subplot I am generating in plotly.我想在我生成的每个子图中在0.09 and -0.09处添加水平线。 Following is my code to do that.以下是我的代码来做到这一点。

  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)

Then I want to save this 4 subplots as jpeg on disk.然后我想将这 4 个子图保存为磁盘上的jpeg How can I do that in python我怎么能在python中做到这一点

Try updating layout of fig object with shapes as below:尝试使用以下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')

The plot will be saved as Temp_plot.jpeg .该图将保存为Temp_plot.jpeg Check the image below.检查下面的图像。 保存的情节

The downside of this method is we need to carefully give axes values to xref and yref with respect to subplots.这种方法的缺点是我们需要仔细为子图的xrefyref提供轴值。

You mentioned that you were ok with a matplotlib solution:你提到你对matplotlib解决方案没问题:

Data:数据:

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)

Plot:阴谋:

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")

Result:结果:

在此处输入图片说明

I'm pretty new to Plotly so maybe the API has just been updated, but it seems there is a much simpler solution, per the documentation here .我对 Plotly 还很陌生,所以也许 API 刚刚更新,但根据此处文档,似乎有一个更简单的解决方案。 One need only use the fig.add_hline() syntax while specifying which subplot (col and row) it should be drawn on, as such:只需要使用fig.add_hline()语法,同时指定应该在哪个子图(col 和 row)上绘制,如下所示:

fig.add_hline(y=1, line_dash="dot", row=1, col=1, line_color="#000000", line_width=2)

This line will instruct Plotly to draw a horizontal line y = 1 on the subplot located at row = 1 ;该行将指示 Plotly 在位于row = 1的子图中绘制一条水平线y = 1 row = 1 col = 1 . col = 1

Alternatively, as noted in the dox, the "all" keyword can be passed as a value for either the row or col argument to instruct plotly to draw the line on (wait for it...) all the subplots!或者,如 dox 中所述,“all”关键字可以作为rowcol参数的值传递,以指示 plotly 在(等待它...)所有子图上绘制线!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM