python - 如何从长度不均匀的列表中创建分组条形图
问题描述
我正在尝试绘制具有不同数据长度的数据组。你知道我如何可视化一个只包含两个对象的女性列表而不用零填充其余对象以获得男性列表的长度吗?
这是我到目前为止得到的代码:
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()
解决方案
您可以为 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。
推荐阅读
- reactjs - React:如何将路径与带有具体路径的参数进行比较
- scala - 如何在我的 scala 项目中使用已编译的 java 类?
- javascript - Amcharts Force-directed-network:如何阻止所有子节点一起渲染
- android - 如何在可缩放和可拖动的图像上绘制多个图钉并避免在缩放和拖动时冻结?
- python - 使用 map() 函数输入整数列表的绝对值
- javascript - 在 ReactJS 中为 RadioButtons 启用 Tab 按下或辅助功能
- python - 在 Plotly Indicator python 中显示相对和绝对差异
- ios - AdMob for iOS 缺少框架错误
- ios - iOS 应用程序仅在“在设备上测试”时接收来自 Firebase 的推送通知
- php - php - 如何生成 MySQL INSERT 语句以使用数组中的多行填充表