手把手教你做一个python+matplotlib的炫酷的数据可视化动图

2023-06-05,,

1.效果图

2.注意:

上述资料是虚拟的,为了学习制作动图,构建的。

仅供学习,

不是真实数据,请别误传。

当自己需要对真实数据进行可视化时,可进行适当修改。

3.代码:

#第1步:导出模块,固定
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import matplotlib.animation as animation #第2步:中文字体显示设置1,导出通用字体设置,可调整
from matplotlib import font_manager
#中文字体显示设置2,引出字体模块和位置
#注意此处字体size大小不设置就是默认,设置或不设置后会发现所有文字或汉字大小都固定在my_font,下面单独设size无效了
my_font = font_manager.FontProperties(fname="/usr/share/fonts/truetype/noto/simsun.ttf",size=14)
#中文字体显示设置,第3步,增加u和fontproperties=my_font,加不加u或r均可以 #第3步:导入数据,可调整,文件名和目录可调整
#将数据下载下来放在指定默认的目录和文件夹下
df = pd.read_csv('4.csv',
usecols=['name', 'group', 'year', 'value'])
#定义全局变量
current_year = 2018 #第4步:定义dff和图片大小设置,可固定
dff=() #定义元组
fig, ax = plt.subplots(figsize=(15, 8)) #第5步:定义7组数据的颜色,group可调整,但颜色值可调整或者不调整
colors = dict(zip(
['安徽', '浙江', '江西', '上海','深圳', '北京', '重庆'],
['#adb0ff', '#ffb3ff', '#90d595', '#e48381','#aafbff', '#f7bb5f', '#eafb50'])) #第6步:从数据中取值,可固定
group_lk = df.set_index('name')['group'].to_dict() #第7步:画图关键设置,可固定
def draw_barchart(year):
dff = df[df['year'].eq(year)].sort_values(by='value', ascending=True).tail(10)
ax.clear() #每次清空、刷新
ax.barh(dff['name'], dff['value'], color=[colors[group_lk[x]] for x in dff['name']])
dx = dff['value'].max() / 200 for i, (value, name) in enumerate(zip(dff['value'], dff['name'])):
#在text里加fontproperties=my_font,注意有my_font的地方size存在的意义不大,目前bug
ax.text(value-dx, i, name, size=20,fontproperties=my_font,
weight=600, ha='right', va='bottom')
ax.text(value-dx, i-.25, group_lk[name], size=10, fontproperties=my_font,
color='#444444', ha='right', va='baseline')
ax.text(value+dx, i, f'{value:,.0f}', size=14, ha='left', va='center')
#显示文字,x=0,y=1.10,坐标,ha=水平对准=水平线平放
#ax.text()格式=(x,y,string,fontsize=15,verticalalignment="top",horizontalalignment="right")
#string=字符串='文字内容' #汉字内容可调整,其他不动
ax.text(0, 1.10, '1968 ~ 2018年我国各部分省和地区GDP变化',
transform=ax.transAxes, size=18, fontproperties=my_font,
weight=600, ha='left') #文字标题,第1层
ax.text(0, 1.04, 'GDP (万亿)', transform=ax.transAxes, size=12,
fontproperties=my_font, color='#777777') #显示文字,第2层
ax.text(1, 0.4, year, transform=ax.transAxes, color='#777777', size=46,
ha='right', weight=800) #右边固定显示动图年份
#va=verticalalignment="top",垂直对准
#ha=horizontalalignment="right",alignment=对准,水平对准
ax.xaxis.set_ticks_position('top') #x轴在上面 ax.set_yticks([]) #默认是显示y轴的名称,左边垂直的城市名字,设为[]就是不显示
ax.margins(0, 0.01) #不设置就是默认值,缩放比例(0,0.05)
ax.grid(which='major', axis='x', linestyle='--') #垂直线,布局和格式
ax.set_axisbelow(True) #默认是true的
#默认是True,False之后不显示黑色线框
plt.box(False)
#以animator形式展现动画
animator = animation.FuncAnimation(fig, draw_barchart, frames=range(1968, 2019)) plt.show() #以plt的形式展现图片

手把手教你做一个python+matplotlib的炫酷的数据可视化动图的相关教程结束。

《手把手教你做一个python+matplotlib的炫酷的数据可视化动图.doc》

下载本文的Word格式文档,以方便收藏与打印。