以正常的barmode ='group'方式绘制具有多个y轴的条形图

时间:2020-03-31 12:23:44

标签: python plotly

我想在python中使用绘图,要绘制带有多个y轴的条形图,因为一个的值明显大于另一个。 Graph showcasing the problem, cant see blue variation due to red's size

我尝试使用plotly.subplots.make_subplots解决此问题,但是我无法让它们像正常的barmode='group'功能一样彼此相邻绘制。

import plotly.graph_objects as go
from plotly.subplots import make_subplots

fig = make_subplots(specs=[[{'secondary_y': True}]])

fig.add_bar(name='group 1',x=x1, y=y1, secondary_y=False)

fig.add_bar(name='group 2', x=x2, y=y2, secondary_y=True)

fig.update_layout(
    xaxis_title='x-axis',
    yaxis_title='y-axis')

这些条形图相互重叠,我已经弄乱了make_suplots的参数。

Problem with Make_subplots

我如何获得理想的结果?

编辑:

我尝试了Jaroslav的答案,并且确实可行。感觉像是次优的实现,并且在第二个y轴上键值切割。

绝对很高兴知道,并且应该在大多数情况下都可以工作,尽管如此,谢谢! enter image description here

2 个答案:

答案 0 :(得分:2)

关键在于正确设置go.Figure()对象中的某些参数。我希望这个例子是不言自明的:

import plotly.graph_objects as go
animals=['giraffes', 'orangutans', 'monkeys']

fig = go.Figure(
    data=[
        go.Bar(name='SF Zoo', x=animals, y=[200, 140, 210], yaxis='y', offsetgroup=1),
        go.Bar(name='LA Zoo', x=animals, y=[12, 18, 29], yaxis='y2', offsetgroup=2)
    ],
    layout={
        'yaxis': {'title': 'SF Zoo axis'},
        'yaxis2': {'title': 'LA Zoo axis', 'overlaying': 'y', 'side': 'right'}
    }
)

# Change the bar mode
fig.update_layout(barmode='group')
fig.show()

结果如下:

enter image description here

答案 1 :(得分:0)

首先:谢谢@JaroslavBezděk的回答,这对我很有帮助。

只需回答由@Joram引起的y轴值图例切割问题: 您可以轻松地重新定位图例。以下示例基于plotly libraries

import plotly.graph_objects as go
animals=['giraffes', 'orangutans', 'monkeys']

fig = go.Figure(
    data=[
        go.Bar(name='SF Zoo', x=animals, y=[200, 140, 210], yaxis='y', offsetgroup=1),
        go.Bar(name='LA Zoo', x=animals, y=[12, 18, 29], yaxis='y2', offsetgroup=2)
    ],
    layout={
        'yaxis': {'title': 'SF Zoo axis'},
        'yaxis2': {'title': 'LA Zoo axis', 'overlaying': 'y', 'side': 'right'}
    }
)

# Change the bar mode and legend layout
fig.update_layout(barmode='group',
                  legend=dict(yanchor="top",y=0.99,xanchor="left",x=0.01))
fig.show()