您需要稍微处理一下您的数据,但这并不需要使用 pandas
。此外,您想要的是堆叠条形图,而不是直方图:
import matplotlib.pyplot as plt
attr_info = {
'Gender': ['m', 'f', 'm', 'm', 'f', 'm', 'm', 'f', 'm', 'f'],
'Age': [9, 43, 234, 23, 2, 95, 32, 63, 58, 42],
'Smoker': ['y', 'n', 'y', 'y', 'n', 'n', 'n', 'n', 'y', 'y']
}
ages_0_10 = [x for x in attr_info['Age'] if x < 10]
ages_10_40 = [x for x in attr_info['Age'] if x >= 10 and x < 40]
ages_40p = [x for x in attr_info['Age'] if x > 40]
gender_m = [x for x in attr_info['Gender'] if 'm' in x]
gender_f = [x for x in attr_info['Gender'] if 'f' in x]
smoker_y = [x for x in attr_info['Smoker'] if 'y' in x]
smoker_n = [x for x in attr_info['Smoker'] if 'n' in x]
locs = [0, 1, 2]
plt.bar(locs[0], len(ages_0_10), width=0.5)
plt.bar(locs[0], len(ages_10_40), bottom=len(ages_0_10), width=0.5)
plt.bar(locs[0], len(ages_40p), bottom=len(ages_0_10) + len(ages_10_40), width=0.5)
plt.text(locs[0], len(ages_0_10) / 2, r'$<10$')
plt.text(locs[0], len(ages_0_10) + 1, r'$[10, 40]$')
plt.text(locs[0], len(ages_0_10) + 5, r'$>40$')
tops = [len(gender_m), len(smoker_y)]
bottoms = [len(gender_f), len(smoker_n)]
plt.bar(locs[1:], bottoms, width=0.5)
plt.bar(locs[1:], tops, bottom=bottoms, width=0.5)
plt.text(locs[1], len(gender_m) / 2, 'm')
plt.text(locs[1], len(gender_m) + 2, 'f')
plt.text(locs[2], len(smoker_y) / 2, 'y')
plt.text(locs[2], len(smoker_n) + 2, 'n')
plt.xticks(locs, ('Age', 'Gender', 'Smoker'))
plt.show()
结果:
![输入图像描述](https://istack.dev59.com/MTdT5.webp)
请查看 pyplot.bar文档 和这个 示例。