我有以下代码(从 Plotly 页面稍作修改)
import plotly.graph_objects as go
from plotly.subplots import make_subplots
# Create figure with secondary y-axis
fig = make_subplots(specs=[[{"secondary_y": True}]])
# Add traces
fig.add_trace(
go.Scatter(x=[1, 2, 3], y=[40, 50, 60], name="yaxis data"),
secondary_y=False,
)
fig.add_trace(
go.Scatter(x=[2, 3, 4], y=[80, 40, 30], name="yaxis2 data"),
secondary_y=True,
)
# Add figure title
fig.update_layout(
title_text="Double Y Axis Example"
)
# Set x-axis title
fig.update_xaxes(title_text="xaxis title")
# Set y-axes titles
fig.update_yaxes(title_text="<b>primary</b> yaxis title", secondary_y=False)
fig.update_yaxes(title_text="<b>secondary</b> yaxis title", secondary_y=True)
fig.show()
Run Code Online (Sandbox Code Playgroud)
这给出了结果
现在您会看到左侧有两个红色圆圈,右侧有一个红色圆圈。您可以看到值 50 没有与同一矩形对齐。
如何使左 Y 轴和右 Y 轴在某一特定点对齐?(大多数情况下为 0)
编辑:我想澄清一下,两个轴(左轴和右轴)的值可能有很大不同。喜欢
我只希望一个值(在本例中为 0)的对齐方式处于同一级别
你可以这样做:
fig.update_layout(yaxis=dict(range=[all_min,all_max]), yaxis2=dict(range=[all_min,all_max]))
使用, 和调整 y 范围scaleanchor
将辅助 y 轴设置为y1
如下所示:fig.update_layout(yaxis2=dict(scaleanchor = 'y1'))
如果图形数据的来源是 pandas 数据框,那么有更优雅的方法来查找全局最大值和最小值,而不仅仅是将它们硬编码在其中。否则,方法将是相同的。
import plotly.graph_objects as go
from plotly.subplots import make_subplots
# Create figure with secondary y-axis
fig = make_subplots(specs=[[{"secondary_y": True}]])
# Add traces
fig.add_trace(
go.Scatter(x=[1, 2, 3], y=[40, 50, 60], name="yaxis data"),
secondary_y=False,
)
fig.add_trace(
go.Scatter(x=[2, 3, 4], y=[80, 40, 30], name="yaxis2 data"),
secondary_y=True,
)
# Add figure title
fig.update_layout(
title_text="Double Y Axis Example"
)
# Set x-axis title
fig.update_xaxes(title_text="xaxis title")
# Set y-axes titles
fig.update_yaxes(title_text="<b>primary</b> yaxis title", secondary_y=False)
fig.update_yaxes(title_text="<b>secondary</b> yaxis title", secondary_y=True)
all_min = 10
all_max = 100
fig.update_layout(yaxis=dict(range=[all_min,all_max]), yaxis2=dict(range=[all_min,all_max]))
# fig.update_layout(yaxis2=dict(scaleanchor = 50))
fig.show()
Run Code Online (Sandbox Code Playgroud)