Plotly:如何控制双Yax的哪个轨迹在前面?

2024-05-16 02:37:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个双y轴图,看起来像这样:

enter image description here

在本例中,钢筋位于次y轴上。然而,我希望队伍排在酒吧前面。我认为做yaxis2=dict(overlaying='y1')可以解决这个问题,但没有什么不同。到目前为止,我提出的唯一一个简单的解决方案是降低条形图的不透明度,这样你就可以看到线条了。当然,尽管有一种方法可以解决我所缺少的问题


Tags: 方法解决方案dict线条酒吧条形图透明度y1
1条回答
网友
1楼 · 发布于 2024-05-16 02:37:00

回答:

次y轴上的轨迹将显示在顶部。不管它是go.Scatter()跟踪还是go.Bar()跟踪

详细信息:

overlaying属性仅适用于具有两个以上y轴的情况,如here

enter image description here

the docs可以看到:

overlaying Parent: layout.xaxis Type: enumerated , one of ( "free" | "/^x([2-9]|[1-9][0-9]+)?$/" | "/^y([2-9]|[1-9][0-9]+)?$/" ) If set a same-letter axis id, this axis is overlaid on top of the corresponding same-letter axis, with traces and axes visible for both axes. If "False", this axis does not overlay any same-letter axes. In this case, for axes with overlapping domains only the highest-numbered axis will be visible.

那么,你的案子呢? 通常,记录道按其添加到fig的顺序显示。但对于具有两个y轴的图形,情况并非如此。看起来您必须切换显示在主轴上的轨迹。第一个代码段生成一个在主轴上带有条形的图形。第二个代码段生成了一个在次轴上带有条形的图形。这也决定了哪个轨迹显示在顶部

代码1:

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.Bar(x=[1, 2, 3], y=[40, 50, 60], name="yaxis data"),
    secondary_y=True,
)

fig.add_trace(
    go.Scatter(x=[1, 2, 3], y=[45, 50, 45], name="yaxis2 data"),
    secondary_y=False,
)

图2(图3)

图1:

enter image description here

代码2:

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.Bar(x=[1, 2, 3], y=[40, 50, 60], name="yaxis data"),
    secondary_y=False,
)

fig.add_trace(
    go.Scatter(x=[1, 2, 3], y=[45, 50, 45], name="yaxis2 data"),
    secondary_y=True,
)


fig.show()

图2:

enter image description here

相关问题 更多 >