首页 > 解决方案 > 有什么方法可以在 plotly express 中实现堆叠或分组条形图

问题描述

我正在尝试在 plotly express 中实现分组条形图(或)堆叠条形图

我已经使用 plotly 实现了它(这很简单),下面是它的代码。数据框中共有六列 ['Rank', 'NOC', 'Gold', 'Silver', 'Bronze', 'Total']

`
trace1=go.Bar(x=olympics_data['NOC'],y=olympics_data['Gold'],marker=dict(color='green',opacity=0.5),name="Gold")
trace2=go.Bar(x=olympics_data['NOC'],y=olympics_data['Silver'],marker=dict(color='red',opacity=0.5),name="Silver")
trace3=go.Bar(x=olympics_data['NOC'],y=olympics_data['Bronze'],marker=dict(color='blue',opacity=0.5),name="Bronze")

data=[trace1,trace2,trace3]

layout = go.Layout(title="number of medals in each category for various countries",xaxis=dict(title="countries"),yaxis=dict(title="number of medals"),
                   barmode="stack")

fig = go.Figure(data,layout)

fig.show()`

输出:

在此处输入图像描述

我期待使用 plotly-express 得到类似的输出。

标签: pythonplotlyplotly-express

解决方案


您可以安排您的数据以px.bar()在此链接中使用。

或者你可以考虑relativebarmode().

barmode (str (default 'relative')) -- 'group'、'overlay' 或 'relative' 之一 在'relative' 模式下,正值的条形堆叠在零之上,负值的条形堆叠在零之下。在“叠加”模式下,条形图相互叠加。在“组”模式下,条形图彼此并排放置。

使用overlay

import plotly.express as px
iris = px.data.iris()
display(iris)
fig = px.histogram(iris, x='sepal_length', color='species', 
                           nbins=19, range_x=[4,8], width=600, height=350,
                           opacity=0.4, marginal='box')
fig.update_layout(barmode='overlay')
fig.update_yaxes(range=[0,20],row=1, col=1)
fig.show()

在此处输入图像描述

使用relative

fig.update_layout(barmode='relative')
fig.update_yaxes(range=[0,20],row=1, col=1)
fig.show()

在此处输入图像描述

使用group

fig.update_layout(barmode='group')
fig.show()

在此处输入图像描述


推荐阅读