首页 > 解决方案 > Plotly:使用辅助 y 轴进行注释

问题描述

从 plotly拿了一个例子。并对其进行了修改,以便第二条轨迹绘制在 secondary_y 轴上。我想使用辅助轴作为参考来注释该线上的一个点。

这是代码:

import plotly.graph_objects as go

fig = make_subplots(specs=[[{"secondary_y": True}]])

fig.add_trace(go.Scatter(
   x=[0, 1, 2, 3, 4, 5, 6, 7, 8],
   y=[0, 11, 31, 21, 41, 31, 41, 61, 51]
))

fig.add_trace(go.Scatter(
   x=[0, 1, 2, 3, 4, 5, 6, 7, 8],
   y=[0, 4, 5, 1, 2, 2, 3, 4, 2]
), secondary_y=True)

fig.add_annotation(
       x=2,
       y=5,
       xref="x",
       yref="y",
       text="max=5",
       showarrow=True,
       font=dict(
           family="Courier New, monospace",
           size=16,
           color="#ffffff"
           ),
       align="center",
       arrowhead=2,
       arrowsize=1,
       arrowwidth=2,
       arrowcolor="#636363",
       ax=20,
       ay=-30,
       bordercolor="#c7c7c7",
       borderwidth=2,
       borderpad=4,
       bgcolor="#ff7f0e",
       opacity=0.8
       )

fig.update_layout()

这样就出来了,注释应该在第二行。 输出,注解不在线

标签: pythonplotly

解决方案


您只需要替换yref="y"yref="y2"in fig.add_annotation()

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=[0, 1, 2, 3, 4, 5, 6, 7, 8],
   y=[0, 11, 31, 21, 41, 31, 41, 61, 51]
))

fig.add_trace(go.Scatter(
   x=[0, 1, 2, 3, 4, 5, 6, 7, 8],
   y=[0, 4, 5, 1, 2, 2, 3, 4, 2]
), secondary_y=True)

fig.add_annotation(
       x=2,
       y=5,
       xref="x",
       yref="y2",
       text="max=5",
       showarrow=True,
       font=dict(
           family="Courier New, monospace",
           size=16,
           color="#ffffff"
           ),
       align="center",
       arrowhead=2,
       arrowsize=1,
       arrowwidth=2,
       arrowcolor="#636363",
       ax=20,
       ay=-30,
       bordercolor="#c7c7c7",
       borderwidth=2,
       borderpad=4,
       bgcolor="#ff7f0e",
       opacity=0.8
       )

fig.show()

在此处输入图像描述


推荐阅读