简体   繁体   中英

matplotlib uneven group size bar charts side-by-side

I am trying to plot groups of data which have different bar sizes and may have different group sizes. How can I group the bars that belong to the same groups (shown as the same color) so that they are side by side? (Similar to this , except the same colors should be side-by-side)

width = 0.50      
groupgap=2
y1=[20,80]
y2=[60,30,10]
x1 = np.arange(len(y1))
x2 = np.arange(len(y2))+groupgap
ind = np.concatenate((x1,x2))
fig, ax = plt.subplots()
rects1 = ax.bar(x1, y1, width, color='r',  ecolor= "black",label="Gender")
rects2 = ax.bar(x2, y2, width, color='b',  ecolor= "black",label="Type")
ax.set_ylabel('Population',fontsize=14)
ax.set_xticks(ind)
ax.set_xticklabels(('Male', 'Female','Student', 'Faculty','Others'),fontsize=14)
ax.legend()

在此输入图像描述

The idea of using a gap between the categories ( groupgap ) is indeed a way to go. You would just have to add the length of the first group as well:

x2 = np.arange(len(y2))+groupgap+len(y1)

Here is the complete example where I used groupgap=1 :

import matplotlib.pyplot as plt
import numpy as np

width = 1      
groupgap=1
y1=[20,80]
y2=[60,30,10]
x1 = np.arange(len(y1))
x2 = np.arange(len(y2))+groupgap+len(y1)
ind = np.concatenate((x1,x2))
fig, ax = plt.subplots()
rects1 = ax.bar(x1, y1, width, color='r',  edgecolor= "black",label="Gender")
rects2 = ax.bar(x2, y2, width, color='b',  edgecolor= "black",label="Type")
ax.set_ylabel('Population',fontsize=14)
ax.set_xticks(ind)
ax.set_xticklabels(('Male', 'Female','Student', 'Faculty','Others'),fontsize=14)
plt.show()

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM