python - 有什么方法可以在 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 得到类似的输出。
解决方案
您可以安排您的数据以px.bar()
在此链接中使用。
或者你可以考虑relative
在barmode()
.
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()
推荐阅读
- axios - cancelToken:ourRequest.token 在 React 钩子中不起作用
- sql - 如何将所有行与列中的相同数据结合起来?
- reactjs - 当 Formik 出现错误时如何显示通用消息
- ios - 使用 AVFoundation 录制视频并将其直接添加到 Swift 中的表格视图中
- javascript - 如何使用 Javascript 删除父元素中重复的数据目标子元素?
- erlang - 如何发出 httpc 请求并附加客户端证书?
- python - 拆分 3D numpy 数组以获取具有满足条件的连续值的所有系列
- python - Pytorch LSTM - 如何在不使用 for 循环的情况下实现它?
- python - MongoDB升/降目标错误值
- reactjs - 在 Material UI DatePicker 中聚焦特定日期