目录
数据导入
我们经常会遇到对比多个统计量随时间变化的图像,比如想知道中国、美国以及欧盟最近几年GDP变化,如下表所示,单位是万亿美元。
中国 | 美国 | 欧盟 | |
---|---|---|---|
2018 | 13.89 | 20.53 | 15.98 |
2019 | 14.28 | 21.38 | 15.69 |
2020 | 14.69 | 21.06 | 15.37 |
2021 | 17.82 | 23.32 | 17.19 |
2022 | 17.96 | 25.46 | 16.64 |
首先,把这些数值写入python
import numpy as np years = np.arange(2018, 2023) areas = (\"PRC\", \"USA\", \"EU\") GDPS = { \'PRC\': (13.89, 14.28, 14.69, 17.82, 17.96), \'USA\': (20.53, 21.38, 21.06, 23.32, 25.46), \'EU\': (15.98, 15.69, 15.37, 17.19, 16.64), }
多组条形图
然后,调用bar
画图,由于每个年份都要绘制中国、美国以及欧盟三个条形图,所以需要合理规划每个条形图占据的宽度。在bar
中,默认每组条形图的x
坐标均为整数,故而下面将每个数据条的宽度设为0.25,并调用bar_label
为这些条形图添加标签,以区分中美欧三个地区的划分
import matplotlib.pyplot as plt x = np.arange(len(years)) width = 0.25 n = 0 for area, gdp in GDPS.items(): offset = width * n rects = plt.bar(x + offset, gdp, width, label=area) plt.bar_label(rects, padding=3) n += 1 plt.ylabel(\'GDP/$trilion\') plt.ylim(10, 28) plt.xticks(x + width, years.astype(str)) plt.legend(loc=\'upper left\') plt.show()
其中,legend
用于调控图例所在位置,upper left
表示将图例放在图像的左上角。如果不想精心设置,则可设为best
,那么matplotli将会自行挑选一个合适的位置放置图例。
效果如下
其中,蓝色表示中国,橘色表示美国,绿色表示欧盟。从这个图就可以非常直观地看出,三者自2018到2022年的GDP变化情况。
堆叠条形图
如果想更加直观地查看2018到2022年间,中、美、欧三个地区的GDP增长情况,那么比较好的方案是绘制堆叠条形图。
堆叠条形图的绘制逻辑是,先画一个数据条,然后在这个数据条之上,再画一个数据条,所以想看增长率,就要用2022年的GDP减去2018年的,
GDPs = { \"2018\": np.array([13.89, 20.53, 15.98]), \"2022\": np.array([17.96, 25.46, 16.64]), } GDPs[\'2022\'] -= GDPs[\'2018\']
然后设置一个条形图的底部,这样每次绘制条形图的时候,都以这个bottom
为底,就可以起到堆叠的效果
bottom = np.zeros(3) for lbl, gdp in GDPs.items(): p = plt.bar(areas, gdp, label=lbl, bottom=bottom) plt.bar_label(p, label_type=\'center\') bottom += gdp plt.ylabel(\'GDP/$trilion\') plt.legend(loc=\"upper right\") plt.show()
结果如图所示
可见,这五年中国的GDP涨了4万亿美元,美国则接近5万亿,而欧盟则增长甚微,给人一种有人退欧的感觉。
© 版权声明
THE END
暂无评论内容