1
votes

I have the following dataframe '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

I am trying to create a vertically stacked bar-chart, with on the x-axis 3 seperate bars: one for 'Percentages_center', one for 'Percentages zone2' and one for 'Percentages total'. 1 bar should represent the percentages of sleeping, low activity, middle activity and high activity.

I've tried this using the following code, but I cant figure out how to make the bar chart:

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()
1
How did my suggestion work out for you?vestland

1 Answers

0
votes

If you're open to plotly.express, I would suggest using

df = df.T # to get your df in the right shape
fig = px.bar(df, x = df.index, y = df.columns)

Plot:

enter image description here

Complete code:

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()