Plotly:使用辅助yaxis进行注释

2024-04-29 16:54:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我拍了一张expamle from plotly。并对其进行修改,使第二个轨迹绘制在第二个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()

这就是结果,注释应该在第二行。 Output, Annotation not on line


Tags: 代码fromimportaddtruego轨迹fig
1条回答
网友
1楼 · 发布于 2024-04-29 16:54:24

您只需要在fig.add_annotation()中用yref="y2"替换yref="y",请参见下面的示例

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

enter image description here

相关问题 更多 >