python - Plotly:如何从 pandas 数据框创建垂直堆叠的条形图?
问题描述
我有以下数据框'df_percentages':
df_percentages
Percentages_center Percentages zone2 Percentages total
Sleeping 77.496214 87.551742 12.202591
Low activity 21.339391 12.286724 81.511021
Middle activity 0.969207 0.124516 5.226317
High activity 0.158169 0.000000 1.009591
我正在尝试创建一个垂直堆叠的条形图,在 x 轴上有 3 个单独的条形图:一个用于“Percentages_center”,一个用于“Percentages zone2”,一个用于“Percentages total”。1 条应代表睡眠、低活动、中等活动和高活动的百分比。
我已经使用以下代码进行了尝试,但我不知道如何制作条形图:
x = ['Center', 'Zone2', 'Total']
plot = px.Figure(data=[go.Bar(
name = 'Sleeping (0-150 MP)',
x = x,
y = df_percentages['Percentages center']
),
go.Bar(
name = 'Low activity (151-2000 MP)',
x = x,
y = df_percentages['Percentages zone2']
),
go.Bar(
name = 'Middle activity (2001-6000 MP)',
x = x,
y = df_percentages['Percentages center']
),
go.Bar(
name = 'High activity (6000-10000)',
x = x,
y = df_percentages['Percentages zone2']
)
])
plot.update_layout(barmode='stack')
plot.show()
解决方案
如果您对 plotly.express 持开放态度,我建议您使用
df = df.T # to get your df in the right shape
fig = px.bar(df, x = df.index, y = df.columns)
阴谋:
完整代码:
import pandas as pd
import plotly.graph_objs as go
import plotly.express as px
df = pd.DataFrame({'Percentages_center': {'Sleeping': 77.496214,
'Low_activity': 21.339391,
'Middle_activity': 0.9692069999999999,
'High_activity': 0.158169},
'Percentages_zone2': {'Sleeping': 87.551742,
'Low_activity': 12.286724000000001,
'Middle_activity': 0.124516,
'High_activity': 0.0},
'Percentages_total': {'Sleeping': 12.202591,
'Low_activity': 81.511021,
'Middle_activity': 5.226317,
'High_activity': 1.009591}})
df = df.T
fig = px.bar(df, x = df.index, y = df.columns)
fig.show()
推荐阅读
- jquery - jQuery datatables 服务器端复杂表创建
- html - 在较小的设备上显示时,表格的一部分会偏向一边
- excel - 如何在excel VBA中为具有命名范围的图表设置源数据
- javascript - 从控制器返回 JavaScript 作为内容或 JavaScriptResult
- pandas - 将数据框打印到带有名称的excel
- blend - 是否可以在支持所有平台的 Uno 平台上使用 Blend for Visual Studio?
- python - 熊猫分隔符功能无法正常工作
- flutter - 如何避免资产中的图像在 Flutter 中“弹出”到屏幕上
- html - 如何在退出引导模板中导入指南针框架?
- amazon-web-services - 在 nosql dynamodb 表中使用分区键查找总记录数的复杂性?