python:数据可视化 - 动态

图片

抖音、快手、B站等上常见的数据统计动态图,视频是如何制作的呢?我们可以通过python的pandas和matplotlib制作出来。

步骤1:安装pandas、matplotlib库

pip install pandas

pip install matplotlib

步骤2:从国家统计局等数据网站找到合适的数据。

https://data.stats.gov.cn/

步骤3:案例中的数据indus.csv。将统计的数据进行处理存储到合适的文件

百度云

链接:https://pan.baidu.com/s/1xIDh7DgiOJ8xTCQW78H27w

提取码:hkn2

步骤4:源码

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib import font_manager

# C:/Windows/Fonts/simhei.ttf 请核实路径,使用自己电脑路径下的字体
my_font = font_manager.FontProperties(fname="C:/Windows/Fonts/simhei.ttf", size=14)
df = pd.read_csv('indus.csv', usecols=['name', 'group', 'year', 'value'])
current_year = 2021

dff = ()
fig, ax = plt.subplots(figsize=(20, 8))

colors = dict(zip(
    ['城镇单位平均工资(元)', '农林牧渔业(元)', '采矿业(元)', '制造业(元)', '电燃水生产供应(元)', '建筑业(元)', '运输仓储邮政(元)',
     '信息计算机软件(元)', '批发零售(元)', '住宿餐饮(元)', '金融(元)', '房地产(元)', '租赁商务服务(元)', '科研技术地质勘查(元)',
     '水利环境公共设施(元)', '居民服务其他服务(元)', '教育城镇(元)', '卫生、社会保障和社会福利(元)', '文化、体育和娱乐(元)',
     '公共管理社会组织(元)'],
    ['#CDB5CD', '#CD4F39', '#FFA07A', '#8B4513', '#EEEED1', '#00CD66', '#CDC673', '#2E8B57', '#6A5ACD', '#53868B',
     '#CDC8B1', '#CDB38B', '#A9A9A9', '#AB82FF', '#2E8B57', '#BCEE68', '#CDBE70', '#8B8386', '#473C8B', '#104E8B']))

group_lk = df.set_index('name')['group'].to_dict()


def draw_barchart(year):
    dff = df[df['year'].eq(year)].sort_values(by='value', ascending=True).tail(20)
    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'])):
        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')

    ax.text(0, 1.10, '2003-2019年我国城镇各行业平均工资',
            transform=ax.transAxes, size=18, fontproperties=my_font,
            weight=600, ha='left')
    ax.text(1, 0.4, '', transform=ax.transAxes, size=12,
            fontproperties=my_font, color='#777777')
    ax.text(1, 0.4, year, transform=ax.transAxes, color='#777777', size=46,
            ha='right', weight=200)

    ax.xaxis.set_ticks_position('top')

    ax.set_yticks([])
    ax.margins(0, 0.06)
    ax.grid(which='major', axis='x', linestyle='--')
    ax.set_axisbelow(True)
    plt.box(False)


animator = animation.FuncAnimation(fig, draw_barchart, frames=range(2003, 2020), interval=600)

# plt.show()  # 调试使用。

# 保存成 gif动图。
animator.save("result.gif", writer='pillow', fps=160)

微信公众号:玩转测试开发
欢迎关注,共同进步,谢谢!

  • 2
    点赞
  • 48
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值