Python绘图库Matplotlib初识
最近刷到了很多数据可视化的视频,然后今天看视频课也正好看到了python的Matplotlib库讲解。课程讲的很有趣,但是有同学觉得还不够小白。看到同学们的评论,我觉得这就是热心群众挺身而出的时候了。
以输出倒逼输入,冲。另外找Matplotlib参考资料的时候我还发现了国家统计局-国家数据网站,感觉这波学完能当场学以致用,统计局网站下载一些数据稍微调试下,可以直接弄成数据可视化的视频。
1、代码行级注释
注:和视频课老师上课演示的代码不完全一致,存在部分,但是大致结构没动
1 import pandas as pd 2 import matplotlib.pyplot as plt 3 import matplotlib.ticker as ticker 4 import matplotlib.animation as animation 5 6 # 导入数据 7 # pandas获取City.csv文件中name、group、year、value四个字段 8 df = pd.read_csv('./City.csv', usecols=['name', 'group', 'year', 'value']) 9 10 # 设置颜色 11 # 映射函数方式来构造字典 12 colors = dict(zip(["India", "Europe", "Asia", "Latin America", "Middle East", "North America", "Africa"], ["#adb0ff", "#ffb3ff", "#90d595", "#e48381", "#aafbff", "#f7bb5f", "#eafb50"])) 13 # 创建城市与洲的对应关系的字典 14 group_lk = df.set_index('name')['group'].to_dict() 15 16 # 创建对象,绘图展示窗口大小设置 17 # 此处等价于fig = plt.figure(figsize=(15, 8));ax = fig.add_subplot(1,1,1) 18 fig, ax = plt.subplots(figsize=(15, 8)) 19 20 21 # 画单年份横着的条形图 22 def draw(current_year): 23 # 获取year为current_year,按value升序排序,获取最后10组数据 24 dff = df[df['year'].eq(current_year)].sort_values(by='value', ascending=True).tail(10) 25 # 清除主坐标轴数据 26 ax.clear() 27 # 遍历dff中数据,以其中name为y轴(纵轴)数据,以其中value为x轴(横轴)数据 28 # 通过城市与洲的对应关系获取洲,再通过洲与颜色对应关系获取颜色,此颜色为数据颜色 29 ax.barh(dff['name'], dff['value'], color=[colors[group_lk[x]] for x in dff['name']]) 30 31 # 获取dff中最大的value除以200作为参考系,方便后续调整标签相对位置 32 dx = dff['value'].max() / 200 33 # 遍历dff的value和name组成的元组 34 # 对每一行条形图的显示效果进行修饰,在行尽头添加name,group,value 35 for i, (value, name) in enumerate(zip(dff['value'], dff['name'])): 36 # 在(value - dx,i)坐标处添加标签,标签内容为name,居右对齐,居下对齐 37 ax.text(value - dx, i, name, size=14, weight=600, ha='right', va='bottom') 38 # 在(value - dx,i- .25)坐标处添加标签,标签内容为name,居右对齐,居下对齐 39 ax.text(value - dx, i - .25, group_lk[name], size=10, color='#444444', ha='right', va='baseline') 40 # 在(value + dx,i)坐标处添加标签,标签内容为格式化的value(浮点数保留0位小数) 41 ax.text(value + dx, i, f'{value:,.0f}', size=14, ha='left', va='center') 42 43 # 使用Axes坐标系【左下角为(0,0)右上角为(1,1)】,在(1,0.4)坐标处添加标签,标签内容为current_year 44 ax.text(1, 0.4, current_year, transform=ax.transAxes, color='#777777', size=46, ha='right', weight=800) 45 # 使用Axes坐标系【左下角为(0,0)右上角为(1,1)】,在(0,1.15)坐标处添加标签,标签内容为Population (thousands) 46 ax.text(0, 1.06, 'Population (thousands)', transform=ax.transAxes, size=12, color='#777777') 47 48 # 设置x轴精度,格式化为浮点数保留0位小数 49 ax.xaxis.set_major_formatter(ticker.StrMethodFormatter('{x:,.0f}')) 50 # 设置x轴位置,放置到顶部 51 ax.xaxis.set_ticks_position('top') 52 # 设置x轴颜色及大小 53 ax.tick_params(axis='x', colors='#777777', labelsize=12) 54 55 # 设置y轴坐标轴为空 56 ax.set_yticks([]) 57 58 # 内边距设置 59 ax.margins(0, 0.01) 60 61 # 设置x轴上的刻度线 62 ax.grid(which='major', axis='x', linestyle='-') 63 # 刻度线显示在页面的最下层 64 ax.set_axisbelow(True) 65 66 # 使用Axes坐标系【左下角为(0,0)右上角为(1,1)】,在(0,1.15)坐标处添加标签,标签内容为'The most populous cities in the world from 2000 to 2018',居左对齐,居上对齐 67 ax.text(0, 1.15, 'The most populous cities in the world from 2000 to 2018', transform=ax.transAxes, size=24, weight=600, ha='left', va='top') 68 69 # 去掉边框 70 plt.box(False) 71 72 73 # 绘制动图,绘制画布为fig,自定义函数为draw,传值给draw参数为2000~2018;即展示效果为2000~2018年条形图的变化 74 animation = animation.FuncAnimation(fig, draw, frames=range(2000, 2019)) 75 76 # 显示动态柱状图 77 plt.show() 78
2、遇到过的问题
问题:pycharm中程序执行无报错,但是animation.FuncAnimation无法播放,只显示一张白画布
解决:按照这边文章:解决:pycharm中动画函数animation.FuncAnimation不起作用,修改pycharm配置即可
3、参考资料
(2)解决:pycharm中动画函数animation.FuncAnimation不起作用
(3)Matplotlib官网
4、个人执行结果