简体   繁体   English

Plotly - 当悬停在共享 x 轴的两个子图上时如何显示 y 值

[英]Plotly - how to display y values when hovering on two subplots sharing x-axis

I have two subplots sharing x-axis, but it only shows the y-value of one subplot not both.我有两个子图共享 x 轴,但它只显示一个子图的 y 值,而不是两个。 I want the hover-display to show y values from both subplots.我希望悬停显示显示两个子图中的 y 值。

Here is what is showing right now:这是现在显示的内容: 图片1

But I want it to show y values from the bottom chart as well even if I am hovering my mouse on the top chart and vice versa.但我希望它也显示底部图表的 y 值,即使我将鼠标悬停在顶部图表上,反之亦然。

Here's my code:这是我的代码:

title = 'Price over time'
err = 'Price'


fig = make_subplots(rows=2, cols=1,
                    vertical_spacing = 0.05,
                    shared_xaxes=True,
                    subplot_titles=(title,""))

# A
fig.add_trace(go.Scatter(x= A_error['CloseDate'], 
                         y = A_error[err], 
                         line_color = 'green',
                         marker_color = 'green',
                         mode = 'lines+markers',
                         showlegend = True,
                         name = "A",
                         stackgroup = 'one'),
              row = 1,
              col = 1,
              secondary_y = False)

# B
fig.add_trace(go.Scatter(x= B_error['CloseDate'], 
                         y = B_error[err], 
                         line_color = 'blue',
                         mode = 'lines+markers',
                         showlegend = True,
                         name = "B",
                         stackgroup = 'one'),
              row = 2,
              col = 1,
              secondary_y = False)

fig.update_yaxes(tickprefix = '$')
fig.add_hline(y=0, line_width=3, line_dash="dash", line_color="black")

fig.update_layout(#height=600, width=1400, 
                  hovermode = "x unified",
                  legend_traceorder="normal")

At this time, I do not believe a Unified hovermode across the subplot is offered.目前,我不相信提供跨子图的Unified hovermode I got the basis for this from here .我从这里得到了这个基础。 There seems to be a workaround , although it will affect some features.似乎有一种解决方法,尽管它会影响某些功能。 In your example the horizontal line does not appear on both graphs.在您的示例中,水平线不会出现在两个图表上。 Since you did not present your data, I applied your code using the data in the reference.由于您没有提供数据,因此我使用参考中的数据应用了您的代码。 In conclusion, you need to decide whether to adopt the horizontal line or the hover line across the subplots.总之,您需要决定在子图中采用水平线还是 hover 线。

import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots

df = px.data.stocks()

title = 'Price over time'
err = 'Price'

fig = make_subplots(rows=2, cols=1,
                    vertical_spacing = 0.05,
                    shared_xaxes=True,
                    subplot_titles=(title,""))

# A
fig.add_trace(go.Scatter(x = df['date'], 
                         y = df['GOOG'], 
                         line_color = 'green',
                         marker_color = 'green',
                         mode = 'lines+markers',
                         showlegend = True,
                         name = "A",
                         stackgroup = 'one'),
              row = 1,
              col = 1,
              secondary_y = False)

# B
fig.add_trace(go.Scatter(x= df['date'], 
                         y = df['AMZN'], 
                         line_color = 'blue',
                         mode = 'lines+markers',
                         showlegend = True,
                         name = "B",
                         stackgroup = 'one'),
              row = 2,
              col = 1,
              secondary_y = False)

fig.update_yaxes(tickprefix = '$')
fig.update_xaxes(type='date', range=[df['date'].min(),df['date'].max()])

fig.add_hline(y=0, line_width=3, line_dash="dash", line_color="black")

fig.update_layout(#height=600, width=1400, 
                  hovermode = "x unified",
                  legend_traceorder="normal")
fig.update_traces(xaxis='x2')

fig.show()

在此处输入图像描述

import plotly.graph_objects as go将 plotly.graph_objects 导入为 go

from plotly.subplots import make_subplots从 plotly.subplots 导入 make_subplots

def plotly_stl( results ): def plotly_stl(结果):

fig = make_subplots( rows=3+len(results.seasonal.columns), cols=1,
                     shared_xaxes=False,
                   )

precision = 2
customdataName=[results.observed.name.capitalize(),
                results.trend.name.capitalize(),
                results.seasonal.columns[0].capitalize(),
                results.seasonal.columns[1].capitalize(),
                results.resid.name.capitalize(),
               ]
customdata=np.stack((results.observed,
                     results.trend,
                     results.seasonal[results.seasonal.columns[0]],
                     results.seasonal[results.seasonal.columns[1]],
                     results.resid,
                     ), 
                     axis=-1
                   )
#print(customdata)
fig.append_trace( go.Scatter( name=customdataName[0], 
                      mode ='lines', 
                      x=results.observed.index,
                      y=results.observed,
                      line=dict(shape = 'linear', #color = 'blue', #'rgb(100, 10, 100)', 
                                width = 2, #dash = 'dash'
                               ),
                      customdata=customdata,                                 
                      hovertemplate='<br>'.join(['Datetime: %{x:%Y-%m-%d:%h}',
                          '<b>'+customdataName[0]+'</b><b>'+f": %{{y:.{precision}f}}"+'</b>',
                          customdataName[1] + ": %{customdata[1]:.2f}",
                          customdataName[2] + ": %{customdata[2]:.2f}",
                          customdataName[3] + ": %{customdata[3]:.2f}",
                          customdataName[4] + ": %{customdata[4]:.2f}",
                          '<extra></extra>',
                                                ]), 
                      showlegend=False,
                      ),
                  row=1, col=1,
                )
fig['layout']['yaxis']['title']= customdataName[0]

fig.append_trace( go.Scatter( name=customdataName[1], 
                      mode ='lines', 
                      x=results.trend.index,
                      y=results.trend,
                      line=dict(shape = 'linear', #color = 'blue', #'rgb(100, 10, 100)', 
                                width = 2, #dash = 'dash'
                               ),
                      customdata=customdata,                                 
                      hovertemplate='<br>'.join(['Datetime: %{x:%Y-%m-%d:%h}',
                          '<b>'+customdataName[1]+'</b><b>'+f": %{{y:.{precision}f}}"+'</b>',
                          customdataName[0] + ": %{customdata[0]:.2f}",
                          customdataName[2] + ": %{customdata[2]:.2f}",
                          customdataName[3] + ": %{customdata[3]:.2f}",
                          customdataName[4] + ": %{customdata[4]:.2f}",
                          '<extra></extra>'
                                                ]),
                      showlegend=False,
                      ),
                  row=2, col=1,
                )
fig['layout']['yaxis2']['title']= customdataName[1]

for i in range( len(results.seasonal.columns) ):
    another=3-i
    fig.append_trace( go.Scatter( name=customdataName[2+i], 
                      mode ='lines', 
                      x=results.seasonal.index,
                      y=results.seasonal[results.seasonal.columns[i]],
                      line=dict(shape = 'linear', #color = 'blue', #'rgb(100, 10, 100)', 
                                width = 2, #dash = 'dash'
                               ),
                      customdata=customdata,           
                      hovertemplate='<br>'.join(['Datetime: %{x:%Y-%m-%d:%h}',
                          '<b>'+customdataName[2+i]+'</b><b>'+f": %{{y:.{precision}f}}"+'</b>',
                          customdataName[0] + ": %{customdata[0]:.2f}",
                          customdataName[1] + ": %{customdata[1]:.2f}",
                          customdataName[another] + f": %{{customdata[{another}]:.{precision}f}}",
                          customdataName[4] + ": %{customdata[4]:.2f}",
                          '<extra></extra>',
                                                ]), 
                      showlegend=False,
                      ),
                  row=3+i, col=1,
                )
    fig['layout']['yaxis'+str(3+i)]['title']= customdataName[2+i]
    
fig.append_trace( go.Scatter( name=customdataName[4], 
                      mode ='lines', 
                      x=results.resid.index,
                      y=results.resid,
                      line=dict(shape = 'linear', #color = 'blue', #'rgb(100, 10, 100)', 
                                width = 2, #dash = 'dash'
                               ),   
                      customdata=customdata,                                 
                      hovertemplate='<br>'.join(['Datetime: %{x:%Y-%m-%d:%h}',
                          '<b>'+customdataName[4]+'</b><b>'+f": %{{y:.{precision}f}}"+'</b>',
                          customdataName[0] + ": %{customdata[0]:.2f}",
                          customdataName[1] + ": %{customdata[1]:.2f}",
                          customdataName[2] + ": %{customdata[2]:.2f}",
                          customdataName[3] + ": %{customdata[3]:.2f}",
                           '<extra></extra>',
                          ]),                            
                      showlegend=False,
                      ),
                  row=3+len(results.seasonal.columns), col=1,
                )
fig['layout']['yaxis'+str(3+len(results.seasonal.columns))]['title']= customdataName[-1]
fig['layout']['xaxis'+str(3+len(results.seasonal.columns))]['title']= 'Datetime'


fig.update_layout(height=800, width=1000,
                  legend_tracegroupgap = 330,
                  hovermode='x unified',#####
                  legend_traceorder="normal",#####
                  #plot_bgcolor='rgba(0,0,0,0)',
                 )
fig.update_traces( xaxis='x{}'.format(str(3+len(results.seasonal.columns))) )#####
                                      
fig.show()

plotly_stl( results_mstl ) plotly_stl(结果_mstl)

you can see the complete code :https://blog.csdn.net/Linli522362242/article/details/128760927 enter image description here another solution code: https://blog.csdn.net/Linli522362242/article/details/128760927 enter image description here可以看到完整的代码:https://blog.csdn.net/Linli522362242/article/details/128760927在这里输入图片描述另一种解决方法代码: https://blog.csdn.net/Linli522362242/article/details/128760927输入图片说明在这里

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

相关问题 Python Plotly:共享 x 轴并按组制作子图 - Python Plotly: Sharing x-axis and making subplots by group 如何在子图 x 轴上对值进行排序 - How to order values on the subplots x-axis 如何使用bokeh添加共享x轴的额外子图? - How to add extra subplots sharing x-axis using bokeh? 如何更改 plotly 中的 x 轴和 y 轴标签? - How to change the x-axis and y-axis labels in plotly? Plotly:如何使子图的 x 和 y 轴标题更大? - Plotly: How to make the x and y axis titles for subplots bigger? 当 plotly 图表中的 x 轴发生变化时,如何自动调整 y 轴? - How do I auto-adjust the y-axis when the x-axis changes in a plotly chart? Plotly:如何在悬停三个 y 布局和一个 x 轴共享图形时显示所有堆叠的 y 轴数据值? - Plotly: How to show all the stacked y axis data values while hovering for three y layout and one x axis shared graph? 为什么这个 Plotly 图形在 Y 轴和 X 轴上悬停? - Why is this Plotly graph is hovering Y and X axis? 如何在子图共享x轴时停止xlim更新 - How to stop xlim updating when subplots share x-axis 带日期的子图:共享相同 X 轴时缺少图表部分 - Subplots with dates: missing parts of the graph when sharing the same X-axis
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM