Home > Back-end >  How to convert grouped bar chart from vertical to horizontal
How to convert grouped bar chart from vertical to horizontal

Time:05-30

How can this vertical grouped bar chart be changed to a horizontal bar chart (grouped, and stacked)? I need help to alter the code such that the bars are displayed horizontally instead of vertically.

import matplotlib.pyplot as plt
import numpy as np

N = 9
labels = ['L', 'S', 'S', 'M', 'W', 'W', 'S', 'R', 'C']    
M_means = [1, 45, 28, 11, 4, 7, 1, 0.02, 0.3]
PO_means = [3, 58, 17, 8, 3, 8, 1, 0.06, 1]
K_means = [1, 44, 30, 11, 3, 7, 1, 0.01, 0.5]

x = np.arange(len(labels))  # the label locations
width = 0.30  # the width of the bars

fig, ax = plt.subplots(figsize=(15, 9))
rects1 = ax.bar(x - width, M_means, width, label='M S and K', color=('#b02a2a'))
rects2 = ax.bar(x, PO_means, width, label='P O S and K', color=('#055cad'))
rects3 = ax.bar(x   width, K_means, width, label='M K', color=('#0b7d53'))

# Add some text for labels, title and custom x-axis tick labels, etc.
ax.set_ylabel('% of workday', fontsize=32)
#ax.set_title('Scores by group and gender')
ax.set_xticks(x) 
ax.set_xticklabels(labels, fontsize=32, rotation=15) 
ax.legend(loc='upper right', frameon=False, fontsize=32, markerscale=2)

ax.bar_label(rects1, size = 32, padding=20, rotation=90) 
ax.bar_label(rects2, size = 32,  padding=20, rotation=90) 
ax.bar_label(rects3, size = 32,  padding=20, rotation=90)
plt.xticks(ha='center') 
for tick in ax.xaxis.get_major_ticks():
    tick.label.set_fontsize(32) 
for tick in ax.yaxis.get_major_ticks():
    tick.label.set_fontsize(32) 
plt.ylim(0, 100) 
plt.gca().spines['right'].set_color('none')
plt.gca().spines['top'].set_color('none')
#fig.tight_layout()
plt.show()

enter image description here

CodePudding user response:

Functionally, only two changes are needed:

  1. Change ax.bar to grouped bars converted to hbars

    CodePudding user response:

    • The easiest solution is to load the data into a enter image description here

      Stacked

      • To manually create the stacked bar without pandas, see enter image description here

  • Related