我正在尝试使用辅助 y 轴在绘图中添加 hline 形状。该图正确显示了两个不同 y 轴的数据,但尽管在 add_hline 函数中使用 yref='y2',但 hline 仍绘制在主轴上。
我意识到我可以使用 add_shape 而不是 hline 来解决这个问题,但我试图确定我是否做错了什么。
import plotly.express as px
import plotly.graph_objects as go
import numpy as np
# simple example with hline
df = px.data.iris()
fig = px.scatter(df, x="petal_length", y="petal_width")
fig.add_traces(go.Scatter(y=np.arange(1, 7), mode="lines+markers", yaxis='y2'))
fig.add_hline(y=2, line_dash='dash', line_color='Red', yref='y2')
fig.update_layout(
width=400,
height=400,
plot_bgcolor="white",
xaxis=dict(linecolor="black"),
yaxis=dict(linecolor="black"),
yaxis2=dict(
title="yaxis2 title",
overlaying="y",
side="right",
linecolor="black",
)
)
fig.update_xaxes(ticks="outside")
fig.update_yaxes(ticks="outside")
fig.show()
Run Code Online (Sandbox Code Playgroud)
您可能发现了 Plotlyadd_hline方法中的一个错误!我可以打开错误报告供 Plotly 团队研究。
现在,您可以使用该add_shape方法并设置参数:xref="paper", x0=0, x0=1覆盖图形的整个宽度。使用yref="y2"并将两者设置y0=2为y1=2按预期工作。
import plotly.express as px
import plotly.graph_objects as go
import numpy as np
# simple example with hline
df = px.data.iris()
fig = px.scatter(df, x="petal_length", y="petal_width")
fig.add_traces(go.Scatter(y=np.arange(1, 7), mode="lines+markers", yaxis='y2'))
## this may be a bug
# fig.add_hline(y=2, line_dash='dash', line_color='Red', yref='paper')
fig.add_shape(type="line",
xref="paper", yref="y2",
x0=0, y0=2, x1=1, y1=2,
line=dict(
color="red",
dash="dash"
),
)
fig.update_layout(
width=400,
height=400,
plot_bgcolor="white",
xaxis=dict(linecolor="black"),
yaxis=dict(linecolor="black"),
yaxis2=dict(
title="yaxis2 title",
overlaying="y",
side="right",
linecolor="black",
)
)
fig.update_xaxes(ticks="outside")
fig.update_yaxes(ticks="outside")
fig.show()
Run Code Online (Sandbox Code Playgroud)