Python Plotly 图,次要 x 轴链接到主要 [英] Python Plotly figure with secondary x axis linked to primary

查看:70
本文介绍了Python Plotly 图,次要 x 轴链接到主要的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在为这个看似简单的任务而苦苦挣扎:如何将两个 x 轴与相关数据对齐.在我的例子中,一个轴是摄氏度,另一个是华氏度.

I've been struggling with this seemingly simple task: How to align two x axis with related data. In my case one axis is in Celsius and the other in Fahrenheit.

我想要实现的是获得两个 x 轴的对齐,以便:

What I want to achieve is to obtain alignment of the two x axis so that:

32°F = 0°C和50°F = 10°C

32°F = 0°C And 50°F = 10°C

通过这种关系,两个数据集将在温度方面对齐.

With this relation, the two datasets will be aligned in terms of temperature.

我希望在同一个图表上设置两个单位,以便查看者可以根据他们习惯的单位来解释数据.

I want to have both unit sets on the same graph so that the viewer can interpret the data according to the units they are used to.

这是我的代码:

import plotly.graph_objects as go
from plotly.subplots import make_subplots
from plotly.graph_objs.layout import YAxis,XAxis,Margin

layout = go.Layout(
    title="Double X Axis Example",
    xaxis=XAxis(
        title="Celcius"
    ),
    xaxis2 = XAxis(
        title="Fahrenheits",
        overlaying= 'x', 
        side= 'top',
    ),
    yaxis=dict(
        title="Y values"
    ),
)

# Create figure with secondary x-axis
fig = go.Figure(layout=layout)

# Add traces
fig.add_trace(
    go.Scatter(x=[10, 20, 30], y=[4.5, 6, 5], name="data set in celcius"),
)

fig.add_trace(
    go.Scatter(x=[40, 60, 80], y=[4, 5, 6.5], name="data set in fahrenheit", xaxis='x2'),
)

fig.show()

这是未对齐轴的结果图(10°C = 40°F!?):

Here is the resulting figure with the unaligned axes (10°C = 40°F !?):

谢谢,

推荐答案

在这种情况下,设置 x 轴的范围可能会有所帮助,如下所示:

In this case it might help to set the ranges for the x-axes, something like this:

fig.add_trace(
    go.Scatter(x=[10, 20, 30], y=[4.5, 6, 5,], name="data set in celcius",xaxis="x1"),
)

fig.add_trace(
    go.Scatter(x=[40, 60, 80], y=[4, 5, 6.5], name="data set in fahrenheit", xaxis='x2'),
)


fig.update_layout(
    xaxis1=dict(range=[0, 100]),
    xaxis2=dict(range=[32, 212]),
    )

...可能会计算 x1 所需的限制,然后以此为基础的 x2 限制.

...possibly calculating the limit needed of x1 and then base x2 limit on that.

这篇关于Python Plotly 图,次要 x 轴链接到主要的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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