0

I would like to create a subplot of bar chart where '% of total' is the y-axis and 'plants' is the x-axis. Also 'brand' will be legend, so in this case 3 different charts for the 3 different 'brands'. Each groups % adds up to 100%. I started with the code below, but got stuck. Please see a sample of the data below and image below;

import pandas as pd
import numpy as np
df = pd.DataFrame({
    'brand':['A','A', 'A', 'B','B', 'B' ,'C','C', 'C'],
    'plants':[0, 1, 2, 0,1,2,0,1,2],
    '% of total':[80, 12, 8, 67, 18, 5,35, 40,25],
    
    })

plt.figure(figsize=(10, 10))
for i, brand in enumerate(['A', 'B', 'C']):

enter image description here

2 Answers2

3

You can use seaborn and catplot:

# Python env: pip install seaborn
# Anaconda env: conda install seaborn
import seaborn as sns
import matplotlib.pyplot as plt

sns.catplot(x='plants', y='% of total', col='brand', data=df, kind='bar')
plt.show()

Output:

enter image description here

Corralien
  • 109,409
  • 8
  • 28
  • 52
0

Does this need to be in a for loop? You could simply grab the relevant rows using pandas.

For example:

my_A_df = df[df['brand'] == A]
plt.hist(my_A_df)
plt.bar(my_A_df['plants'], my_A_df['% of total'])

This will work for generating a barplot for each. Not sure if this is within the bounds of your problem but happy to edit if necessary.

rsenne
  • 142
  • 6