【问题标题】:Plotly: How to create a vertically stacked bar chart from a pandas dataframe?Plotly:如何从 pandas 数据框创建垂直堆叠的条形图?
【发布时间】:2020-11-15 13:00:08
【问题描述】:

我有以下数据框“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()

【问题讨论】:

  • 我的建议对你有什么效果?

标签: python pandas plotly


【解决方案1】:

如果您愿意使用 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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-07
    • 2022-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-23
    • 1970-01-01
    相关资源
    最近更新 更多