python制作动态排序图
2023-09-14 08:59:07 时间
一、代码
import pandas as pd import matplotlib.pyplot as plt import matplotlib.ticker as ticker import matplotlib.animation as animation df = pd.read_csv(r'动态排序数据.csv', usecols=['name', 'group', 'year', 'value']) colors = dict(zip( ['India', 'Europe', 'Asia', 'Latin America', 'Middle East', 'North America', 'Africa'], ['#adb0ff', '#ffb3ff', '#90d595', '#e48381', '#aafbff', '#f7bb5f', '#eafb50'] )) group_lk = df.set_index('name')['group'].to_dict() fig, ax = plt.subplots(figsize=(15, 8)) 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'])): ax.text(value - dx, i, name, size=14, weight=600, ha='right', va='bottom') 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') # ... polished styles ax.text(1, 0.4, year, transform=ax.transAxes, color='#777777', size=46, ha='right', weight=800) ax.text(0, 1.06, 'Population (thousands)', transform=ax.transAxes, size=12, color='#777777') 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([]) ax.margins(0, 0.01) ax.grid(which='major', axis='x', linestyle='-') ax.set_axisbelow(True) ax.text(0, 1.11, 'The most populous cities in the world from 1968 to 2018', transform=ax.transAxes, size=24, weight=600, ha='left') ax.text(1, 0, 'by maple', transform=ax.transAxes, ha='right',size=15, color='#777777', bbox=dict(facecolor='white', alpha=0.8, edgecolor='white')) plt.box(False) animator = animation.FuncAnimation(fig=fig, func=draw_barchart, frames=range(1968, 2019)) animator.save("动态排序.gif")
数据地址:
https://pan.baidu.com/s/1Qml2z48B4-6PEB1Pjg4v_w
提取密码:2jb4
相关文章
- python电脑版微信-微信PC版的API接口 | 可通过Python调用微信功能
- Python爬虫01——第一个小爬虫
- Python里divmod_python yield函数
- Python数组切片_python print数组
- 在python中用来安装第三方库的常用工具_什么库用于安装管理Python扩展包
- python type error是什么意思_Python 报错 TypeError:’DoesNotExist’对象不可调用
- Python基础-12 虚拟环境和包
- opencv(4.5.3)-python(十五)--图像梯度
- Python 异步执行 Threading
- Python实现KS曲线
- Python人工智能:基于sklearn的随机森林分类算法实现方法
- Python封装机制及实现方法
- python连接mysql查询数据示例详解编程语言
- Linux中运行Python文件的步骤(linux运行python文件)
- Python输出函数print()总结(python print())详解编程语言
- python工具——diagrams详解编程语言
- Python与MongoDB 无缝连接(python连接mongodb)
- Linux查看Python安装路径的方法(linux查看python安装路径)
- 运维学python之爬虫基础篇(四)Cookie
- Python(Tornado)模拟登录小米抢手机
- Python实现同时兼容老版和新版Socket协议的一个简单WebSocket服务器
- Python爬取Coursera课程资源的详细过程