在绘制一般的柱状图后,我们希望绘制对比的柱状图
import matplotlib as mpl
import matplotlib.pyplot as plt
mpl.rcParams['font.sans-serif'] = ['FangSong']
mpl.rcParams['axes.unicode_minus'] = False
with open(r'D:\Pycharm\PythonProject\Examples\Material\csv\中国人口年度数据.csv', 'r') as file:
text = file.readlines()
text = [word.strip().split(',') for word in text]
year = [i for i in text[0]][1:]
# print(text)
# print(year)
year.reverse()
man = [int(i) for i in text[2][1:]]
woman = [int(i) for i in text[3][1:]]
man.reverse()
woman.reverse()
# print(man)
plt.figure(figsize=(10,6))
# 以下的方法画不出对比图
# plt.bar(year, man, color='g', label='man')
# plt.bar(year, woman, color='r', label='woman')
# plt.show()
X = [x*2 for x in range(20)]
Y = [x+0.8 for x in X] # X和Y刚好连在一起
plt.bar(X, man, color='g',label='man')
plt.bar(Y,woman, color='r',label='woman')
# 需要解决的x轴的标签问题
# plt.xticks([x+0.4 for x in X],year, rotation=20) # 第一个参数是位置,第二个参数是名称,第三个是旋转角度
plt.xticks([x+0.4 for x in X], year, fontsize=8) # 设置fontsize,调整标签字体大小
plt.ylim(50000,75000)
plt.yticks(range(50000,75000,1000))
plt.legend(loc=8) # 调整显示的位置
plt.title('中国人口男女对比柱状图')
# plt.savefig(r'D:\Pycharm\PythonProject\Examples\Material\png\中国人口男女对比.png', dpi=200) # 提高清晰度
plt.show()
结果展示如下
如果有问题,欢迎评论区留言交流