将多个 Y 轴与 Plotly 中的一个值对齐 [英] Align Multiple Y axis to one value in Plotly

查看:64
本文介绍了将多个 Y 轴与 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

推荐答案

你可以这样做:

  1. 为您的 y 轴设置(或查找)适当的最小值和最大值,
  2. 使用 fig.update_layout(yaxis=dict(range=[all_min,all_max]), yaxis2=dict(range=[all_min,all_max]))
  3. 将辅助 y 轴的 scaleanchor 设置为 y1,如下所示:fig.update_layout(yaxis2=dict(scaleanchor = 'y1'))
  1. Set (or find) appropriate minimum and maximum values for your y-axes,
  2. adjust your y ranges using fig.update_layout(yaxis=dict(range=[all_min,all_max]), yaxis2=dict(range=[all_min,all_max])), and
  3. set the scaleanchor of your secondary y-axis to y1 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆