首页 > 解决方案 > 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()

标签: pythonpandasplotly

解决方案


如果您对 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()

推荐阅读