Home > Blockchain >  How to plot pandas series' using different contents on the same stacked bar plot?
How to plot pandas series' using different contents on the same stacked bar plot?

Time:08-04

I want to display the following data using the dictionary names (category1, category2 etc) as the y-axis and the float values inside as the x-axis. Using a stacked bar plot, where the total height of each column (category) is the sum of the values inside, and each key name is a separate colour.

category1 = {A: 23.5, B: 48, C: 32.4}
category2 = {D: 12, E: 54.3, F: 65}
category2 = {G: 7.5, H: 43, I: 24.8}

I hope this makes sense. It's proving very difficult for me to wrap my head around and hence also immensely struggling to google the solution.

Thank you in advance

CodePudding user response:

Given the data that you provided, this is one way to do it...

category1 = {'A': 23.5, 'B': 48, 'C': 32.4}
category2 = {'D': 12, 'E': 54.3, 'F': 65}
category3 = {'G': 7.5, 'H': 43, 'I': 24.8}
df = pd.DataFrame([category1,category2,category3])
df.rename(index = {0:'Category1', 1:'Category2', 2:'Category3'}, inplace=True)
ax = df.plot.barh(stacked=True)
ax.legend(loc='best')
plt.show()

Plot

enter image description here

CodePudding user response:

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
df = pd.DataFrame({
        'level':['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'],
        'value':[23.5, 48, 32.4, 12, 54.3, 65, 7.5, 43, 24.8],
        'category':['category1', 'category1', 'category1', 'category2', 'category2', 'category2', 'category2', 'category2', 'category2']
        })
df.set_index('level', inplace=True)
df
###
       value   category
level                  
A       23.5  category1
B       48.0  category1
C       32.4  category1
D       12.0  category2
E       54.3  category2
F       65.0  category2
G        7.5  category2
H       43.0  category2
I       24.8  category2

Plot

data = df.pivot_table(columns='category', values='value', index='level').T
fig = plt.figure()
color_map = {'A':'#264653', 'B':'#287271', 'C':'#2a9d8f', 'D':'#8ab17d', 'E':'#e9c46a', 'F':'#efb366', 'G':'#f4a261', 'H':'#ee8959', 'I':'#e76f51'}
data.plot(kind='barh', stacked=True, figsize=(10,10), color=color_map)
plt.legend(loc='upper left', bbox_to_anchor=(1, 1))
plt.show()

enter image description here

  • Related