lualu.txt里面存放文件:
Vijayanagar,India,1537,485.2,India,Vijayanagar - India,485.6,15.335,76.462
Vijayanagar,India,1538,484.8,India,Vijayanagar - India,485.2,15.335,76.462
Vijayanagar,India,1539,484.4,India,Vijayanagar - India,484.8,15.335,76.462
Vijayanagar,India,1540,484,India,Vijayanagar - India,484.4,15.335,76.462
Vijayanagar,India,1541,483.6,India,Vijayanagar - India,484,15.335,76.462
Vijayanagar,India,1542,483.2,India,Vijayanagar - India,483.6,15.335,76.462
Vijayanagar,India,1543,482.8,India,Vijayanagar - India,483.2,15.335,76.462
Vijayanagar,India,1544,482.4,India,Vijayanagar - India,482.8,15.335,76.462
Vijayanagar,India,1545,482,India,Vijayanagar - India,482.4,15.335,76.462
Vijayanagar,India,1546,481.6,India,Vijayanagar - India,482,15.335,76.462
Vijayanagar,India,1547,481.2,India,Vijayanagar - India,481.6,15.335,76.462
Vijayanagar,India,1548,480.8,India,Vijayanagar - India,481.2,15.335,76.462
Vijayanagar,India,1549,480.4,India,Vijayanagar - India,480.8,15.335,76.462
Vijayanagar,India,1550,480,India,Vijayanagar - India,480.4,15.335,76.462
Vijayanagar,India,1551,480,India,Vijayanagar - India,480,15.335,76.462
Vijayanagar,India,1552,480,India,Vijayanagar - India,480,15.335,76.462
Vijayanagar,India,1553,480,India,Vijayanagar - India,480,15.335,76.462
Vijayanagar,India,1554,480,India,Vijayanagar - India,480,15.335,76.462
Vijayanagar,India,1555,480,India,Vijayanagar - India,480,15.335,76.462
Vijayanagar,India,1556,480,India,Vijayanagar - India,480,15.335,76.462
Vijayanagar,India,1557,480,India,Vijayanagar - India,480,15.335,76.462
Vijayanagar,India,1558,480,India,Vijayanagar - India,480,15.335,76.462
Vijayanagar,India,1559,480,India,Vijayanagar - India,480,15.335,76.462
Vijayanagar,India,1560,480,India,Vijayanagar - India,480,15.335,76.462
Vijayanagar,India,1561,480,India,Vijayanagar - India,480,15.335,76.462
Vijayanagar,India,1562,480,India,Vijayanagar - India,480,15.335,76.462
Vijayanagar,India,1563,480,India,Vijayanagar - India,480,15.335,76.462
Vijayanagar,India,1564,480,India,Vijayanagar - India,480,15.335,76.462
Vijayanagar,India,1565,480,India,Vijayanagar - India,480,15.335,76.462
代码部分:
# 导入库函数
import random
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import matplotlib.animation as animation
from IPython.display import HTML
import matplotlib
#防止动漫内存太大,报错
matplotlib.rcParams['animation.embed_limit'] = 2**128
# 控制中文显示https://blog.csdn.net/weixin_44301621/article/details/103531398
plt.rcParams['font.sans-serif']=['SimHei']
plt.rcParams['axes.unicode_minus']=False#pandas读取数据,且去列名分别为name,group,year和value的值;
#url = 'https://gist.githubusercontent.com/johnburnmurdoch/4199dbe55095c3e13de8d5b2e5e5307a/raw/fa018b25c24b7b5f47fd0568937ff6c04e384786/city_populations'
#df = pd.read_csv(url, usecols=['name', 'group', 'year', 'value'])
#df.head()
df = pd.read_csv(r'../lualu.txt',encoding='gbk',usecols=[ 'name', 'group','year', 'value'])#导入random函数,randomcolor用于生成颜色代码
# randomcolor生成颜色代码原理,
# 【1-9/A-F】15个数字随机组合成6位字符串前面再加上一个“#”号键
import random
def randomcolor():colorlist = ['1','2','3','4','5','6','7','8','9','A','B','C','D','E','F']color =''for i in range(6):color += random.choice(colorlist)return '#'+ color# 对地区列表进行去重,分类;
area_list1 = set(df['name'])# color_list用于存放随机生成颜色代码个数
# 因为后面区域个数 要与颜色个数保持一致,这里用了len函数;
color_list = []
for i in range(len(area_list1)):str_1 = randomcolor()color_list.append(str_1)str_1 = randomcolor()# area_list转化为列表
area_list_1 = [i for i in area_list1]
print(color_list)
print(area_list_1)#colors表示 所在城市:颜色 一一对应字典形式;
colors =dict(zip(area_list_1,color_list))
print(colors)#group_lk为 城市:所在区域 --对应字典形式;
group_lk = df.set_index('name')['group'].to_dict()
print(group_lk)# 用plt加理图表,figsize表示图标长宽,ax表示标签
fig, ax = plt.subplots(figsize=(16, 9))# dras_barchart生成current_year这一年各城市人口基本情况;
def draw_barchart(current_year):# dff对year==current_year的行,以value从升序方式排序,取后十名也就是最大值;dff = df[df['year'].eq(current_year)].sort_values(by='value', ascending=True).tail(15)# 所有坐标、标签清除ax.clear()# 显示颜色、城市名字ax.barh(dff['name'], dff['value'], color=[colors[x] for x in dff['name']])dx = dff['value'].max() / 200# ax.text(x,y,name,font,va,ha)# x,y表示位置;# name表示显示文本;# va,ba分别表示水平位置,垂直放置位置;for i, (value, name) in enumerate(zip(dff['value'], dff['name'])):# ax.text(value - dx, i, name, size=14, weight=600, ha='right', va='center')ax.text(value + dx, i, name, size=14, weight=600, ha='left', va='center')# ax.text(value - dx, i - .25, group_lk[name], size=10, color='#444444', ha='right', va='baseline')# ax.text(value + dx, i, f'{value:,.0f}', size=14, ha='left', va='center')ax.text(value - dx, i, f'{value:,.0f}', size=12, ha='right', va='center')# ax.transAxes表示轴坐标系,(1,0.4)表示放置位置ax.text(1, 0.4, current_year, transform=ax.transAxes, color='#777777', size=46, ha='right', weight=800)ax.text(0, 1.06, '国内生产总值·GDP(亿元)', transform=ax.transAxes, size=12, color='#777777')# set_major_formatter表示刻度尺格式;ax.xaxis.set_major_formatter(ticker.StrMethodFormatter('{x:,.0f}'))ax.xaxis.set_ticks_position('top')ax.tick_params(axis='x', colors='#777777', labelsize=12)ax.set_yticks([])# margins表示自动缩放余额;ax.margins(0, 0.01)# 设置后面的网格ax.grid(which='major', axis='x', linestyle='-')# 刻度线和网格线是在图标上方还是下方,True为下方ax.set_axisbelow(True)# ax.text(0.5, 1.15, '2000-2019年各省市区国内生产总值(前15)', transform=ax.transAxes, size=16, weight=600, ha='center', va='top')ax.text(1, 0, '数据来源:国家统计局', transform=ax.transAxes, color='#777777', ha='right', bbox=dict(facecolor='white', alpha=0.8, edgecolor='white'))# 取消图表周围的方框显示plt.box(False)# 绘制2018年各城市人口情况
# draw_barchart(2019)
# fig, ax = plt.subplots(figsize=(15, 30))
with plt.xkcd():fig, ax = plt.subplots(figsize=(15, 8))draw_barchart(2019)#将原来的静态图拼接成动画
fig, ax = plt.subplots(figsize=(16, 9))
animator = animation.FuncAnimation(fig, draw_barchart, frames=range(2000, 2019))
#保存到jshtml
HTML(animator.to_jshtml())#生成video,并保存至指定文件夹中
import os
ffmpegpath = os.path.abspath(r"F:\硬件开发工具\ffmpeg-N-101988-g988f2e9eb0-win64-gpl-shared\bin\ffmpeg.exe")
matplotlib.rcParams["animation.ffmpeg_path"] = ffmpegpathfig, ax = plt.subplots(figsize=(16, 9))
animator = animation.FuncAnimation(fig, draw_barchart, frames=range(2000, 2020))
writer = animation.FFMpegWriter(fps=1)
animator.save('E:/huitao.mp4',writer=writer)
演示效果:
不了解ffmpeg的请转向:https://www.cnblogs.com/xiezhidong/p/6924775.html
参考地址:
https://blog.csdn.net/weixin_42512684/article/details/104286367
https://my.oschina.net/u/4600229/blog/4768216