首页 > 解决方案 > 如何从长度不均匀的列表中创建分组条形图

问题描述

我正在尝试绘制具有不同数据长度的数据组。你知道我如何可视化一个只包含两个对象的女性列表而不用零填充其余对象以获得男性列表的长度吗?

这是我到目前为止得到的代码:

import matplotlib
import matplotlib.pyplot as plt
import numpy as np

labels = ['G1', 'G2', 'G3', 'G4']
male = [1, 3, 10, 20]
female = [2, 7]

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

fig, ax = plt.subplots()
rects1 = ax.bar(x - width/2, male, width, label='male')
rects2 = ax.bar(x + width/2, female, width, label='female')

# Add some text for labels, title and custom x-axis tick labels, etc.
ax.set_xticks(x)
ax.set_xticklabels(labels)
ax.legend()

fig.tight_layout()
plt.show()

标签: pythonmatplotlib

解决方案


您可以为 x 位置创建两个不同的数组:

import matplotlib
import matplotlib.pyplot as plt
import numpy as np

labels = ['G1', 'G2', 'G3', 'G4']
male = [1, 3, 10, 20]
female = [2, 7]

x_male = np.arange(len(male))
x_female = np.arange(len(female))

offset_male = np.zeros(len(male))
offset_female = np.zeros(len(female))

shorter = min(len(x_male), len(x_female))

width = 0.35  # the width of the bars

offset_male[:shorter] = width/2
offset_female[:shorter] = width/2

fig, ax = plt.subplots()
rects1 = ax.bar(x_male - offset_male, male, width, label='male')
rects2 = ax.bar(x_female + offset_female, female, width, label='female')

也就是说,此解决方案仅在较短列表末尾缺少值时才有效。对于列表中缺少的值,最好按照@desert_ranger 的建议使用 None 或 np.nan。


推荐阅读