前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >用Python优雅地制作动态条形图

用Python优雅地制作动态条形图

作者头像
lyhue1991
发布2021-06-15 10:04:11
4620
发布2021-06-15 10:04:11
举报

公众号“算法美食屋”后台回复关键字:动态图,可添加作者微信获取完整代码和人口数据集。

先上图片:

再上视频:

最后上代码:

代码语言:javascript
复制
import numpy as np 
import pandas as pd 
import pandas_alive
from matplotlib import pyplot as plt
import imageio

plt.rcParams['animation.writer'] = 'html'
plt.rcParams['font.family'] = ['sans-serif']
plt.rcParams['font.sans-serif'] = ['SimHei']

def html_to_gif(html_file, gif_file, duration=0.1):
    path = html_file.replace(".html","_frames")
    images = [os.path.join(path,x) for x in sorted(os.listdir(path))]
    frames = [imageio.imread(x) for x in images]
    imageio.mimsave(gif_file, frames, 'gif', duration=duration)
    return gif_file


df = pd.read_csv('./data/pop_amount.csv')
df["year"] = [str(x) for x in df["year"]]
df['year'] = pd.to_datetime(df['year'])
df = df.set_index("year")
df.columns = [x if "自治区" not in x else x[0:2] for x in df.columns]

html_file = "population_bar_race.html"
gif_file = html_file.replace(".html",".gif")
mp4_file =  html_file.replace(".html",".mp4")

def current_total(values):
    total = values.sum()/10000
    s = '中国大陆总人口: {:.2f}亿'.format(total)
    return {'x': .90, 'y': .2, 's': s, 'ha': 'right', 'size': 11}

chart = df.plot_animated(filename = html_file,title="中国大陆各省市历年人口变迁",
        figsize = (6,4),dpi=144,period_summary_func=current_total,
        n_visible=31,bar_texttemplate = '{x:.0f}',filter_column_colors = True,period_fmt="%Y年")

html_to_gif(html_file,gif_file,duration = 0.1)

主要是使用了pandas_alive这个库的功能,可以非常方便地制作条形图竞赛。

收工。?

公众号“算法美食屋”后台回复关键字:动态图,可添加作者微信获取完整代码和人口数据集。

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2021-05-22,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 算法美食屋 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档