python - matplotlib 不均匀组大小条形图并排

标签 python matplotlib

我正在尝试绘制具有不同条形大小并且可能具有不同组大小的数据组。如何将属于同一组(显示为相同颜色)的条形图分组,以便它们并排放置? (类似于 this ,除了相同的颜色应该并排)

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()

enter image description here

最佳答案

在类别之间使用间隙 (groupgap) 的想法确实是一种可行的方法。您还需要添加第一组的长度:

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

这是我使用 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()

enter image description here

关于python - matplotlib 不均匀组大小条形图并排,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41880015/

相关文章:

python - Matplotlib:避免 X 轴拥塞

python - 如何在不知道路径的情况下从另一个相对文件夹导入?

python - Python函数中返回值的数量不同

python - 如何将文本放在 3D 条形图的顶部

python-3.x - 找出散点图中最密集区域的中心

python - 如何在 ubuntu 上为 python ML 安装软件包?

python - 如何告诉 Python 不要解释字符串中的反斜杠?

python - Django 模型表单集和命名 url

python - 带有 seaborn 的 Jointplot 多索引列

python/matplotlib 绘图相当于 R 的符号图?