将多个 Y 轴与 Plotly 中的一个值对齐 [英] Align Multiple Y axis to one value in Plotly
问题描述
我有以下代码(从 Plotly 的页面稍作修改)
I have the following code (slightly modified from Plotly's page)
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()
结果如下
现在您可以看到左侧的两个红色圆圈和右侧的一个红色圆圈.可以看到值 50 没有对齐到同一个矩形.
Now you see the two red circles on on the left and one on the right. You can see that the value 50 is not aligned to the same rect.
如何使左 Y 轴和右 Y 轴在一个特定点对齐?(在大多数情况下为 0)
How can I make that the left Y axis and the right Y axis are aligned at one particular point? (in the majority of cases it would be 0)
我想澄清两个轴(左轴和右轴)中的值可能有很大不同.喜欢
I would like to clarify that the values in both axis (left and right) can be widely different. Like
我只希望一个值(在本例中为 0)的对齐处于同一级别
I just want the alignment of one value (in this case the 0) to be at the same level
推荐答案
你可以这样做:
- 为您的 y 轴设置(或查找)适当的最小值和最大值,
- 使用
fig.update_layout(yaxis=dict(range=[all_min,all_max]), yaxis2=dict(range=[all_min,all_max]))
和 - 将辅助 y 轴的
scaleanchor
设置为y1
,如下所示:fig.update_layout(yaxis2=dict(scaleanchor = 'y1'))
- Set (or find) appropriate minimum and maximum values for your y-axes,
- adjust your y ranges using
fig.update_layout(yaxis=dict(range=[all_min,all_max]), yaxis2=dict(range=[all_min,all_max]))
, and - set the
scaleanchor
of your secondary y-axis toy1
like this:fig.update_layout(yaxis2=dict(scaleanchor = 'y1'))
剧情:
如果您的图形数据的来源是 Pandas 数据框,那么找到全局最大值和最小值的方法比仅仅在其中进行硬编码有更优雅的方法.否则,方法将是相同的.
If the soruce of your figure data is a pandas dataframe, there are more elegant ways of finding global max and min values than just hard-coding them in there. Otherwise, the approach will be the same.
这篇关于将多个 Y 轴与 Plotly 中的一个值对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!