0

I have 5 charts that are results from a for loop and I would like to arrange neatly in a 3x2 format. The for loop results does not seem to fill the subplots and as though they are processed on a seperate figure. I have tried repositioning the subplot code within and outside of the for loop but none of it works. I would like to know how to fill a subplot with results from a for loop

This is my code

top_stages = ['Post-harvest', 'Households', 'Retail', 'Food Services', 'Export']
colors = ['m', 'b', 'g', 'c', 'orange']

#finding mean of loss percentage for top stages
top_stage_df = food_waste_clean[food_waste_clean['food_supply_stage'].isin(top_stages)]
mean_loss_top_stage = top_stage_df['loss_percentage'].mean()

#set up plot figure
plt.subplots(3,2)

#for loop to find mean loss grouped by country for each food supply stage
for stage, c in zip(top_stages, colors):
    stage_df = food_waste_clean[food_waste_clean['food_supply_stage']==stage]
    stage_group = stage_df.groupby('country').mean()
    
#boolean filter stage_group by condition that loss percentage is higher or equal to mean    
    stage_group = stage_group[stage_group['loss_percentage'] >= mean_loss_top_stage]
    stage_sorted = stage_group.sort_values(by='loss_percentage').reset_index()
    
#plot charts with results of groupby
    plt.barh(stage_sorted['country'], stage_sorted['loss_percentage'], color=c, label='mean loss percentage')
    plt.title('Countries with '+ stage + ' food loss')
    plt.axvline(mean_loss_top_stage, color='r',  ls=':', label='total mean loss for all 5 stages')
    plt.legend(bbox_to_anchor=(1.02, 1), loc='upper left')
    plt.xlim(0, 50)
    plt.show()

snippet of chart image

Yanchoo Y
  • 1
  • 1

0 Answers0