来源:好完美 浏览次数: 发布时间:2022-07-10 09:15:16
来源////blob//-race-.ipynb
代码获取方式请在【公众号:邓和他】后台回复关键词“动态排序图”。如果觉得有用,请转发支持
这种图表在国外被称为Bar Chart Race。通过这张图表,你可以观察到公司的兴衰和国家的兴衰。
我用中文数据测试了一下,可以达到80%的效果。虽然没有原作者那么完美漂亮,但基本够用了。
读取空中客流量数据
在国家统计局下载主要国家(地区)年度航空客运量数据/.htm?cn=C01
import pandas as pd
import warnings
warnings.filterwarnings('ignore')
df = pd.read_excel('国际数据主要国家(地区)年度数据.xls', skiprows=[0, 1, 2])
df.head()
让我们看看 2001 年排名前 10 的国家/地区
df2 = df[['地区', '2001年']].sort_values(by='2001年', ascending=False).head(10)
df2.sort_values(by='2001年', ascending=True, inplace=True)
df2
基本地图
我们先来看看最基本的样子完美国际ss帽子代码,有点简陋
%matplotlib inline
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import matplotlib.animation as animation
from IPython.display import HTML
#显示中文(可能还会显示不了,请自行百度解决中文问题)
plt.rcParams['font.sans-serif']=['SimHei'] fig, ax = plt.subplots(figsize=(15, 8)) ax.barh(df2['地区'], df2['2001年'])
颜色标签
我们给城市条形图上色完美国际ss帽子代码,这里原作者使用了7种颜色的rgb码。
我的新数据有 47 个国家,所以这 7 种颜色被重复使用了几次。
注意:城市和颜色的长度为 47
colors = ['#adb0ff', '#ffb3ff', '#90d595', '#e48381', '#aafbff', '#f7bb5f', '#eafb50',
'#adb0ff', '#ffb3ff', '#90d595', '#e48381', '#aafbff', '#f7bb5f', '#eafb50',
'#adb0ff', '#ffb3ff', '#90d595', '#e48381', '#aafbff', '#f7bb5f', '#eafb50',
'#adb0ff', '#ffb3ff', '#90d595', '#e48381', '#aafbff', '#f7bb5f', '#eafb50',
'#adb0ff', '#ffb3ff', '#90d595', '#e48381', '#aafbff', '#f7bb5f', '#eafb50',
'#adb0ff', '#ffb3ff', '#90d595', '#e48381', '#aafbff', '#f7bb5f', '#eafb50',
'#adb0ff', '#ffb3ff', '#90d595', '#e48381', '#aafbff']
#给每个国家随机分配颜色
countrycolors = dict()
countrys = set(df['地区'])
for color, country in zip(colors, countrys):
countrycolors[country] = color
countrycolors
运行
{'巴勒斯坦': '#adb0ff',
'伊拉克': '#ffb3ff',
'越南': '#90d595', '土库曼斯坦': '#e48381', '阿曼': '#aafbff', '乌兹别克斯坦': '#f7bb5f', '塞浦路斯': '#eafb50', '新加坡': '#adb0ff', ..... '斯里兰卡': '#adb0ff', '韩国': '#ffb3ff', '老挝': '#90d595', '尼泊尔': '#e48381', '印度': '#aafbff'}
排名前 10 的国家/地区
fig, ax = plt.subplots(figsize=(15, 8))
#排名前10的国家
ax.barh(df2['地区'], df2['2001年'], color=[countrycolors[c] for c in df2['地区']])
for i, (value, country) in enumerate(zip(df2['2001年'], df2['地区'])):
ax.text(value, i, country, size=14, weight=600, ha='right', va='bottom')
ax.text(value, i, f'{value:,.0f}', size=14, ha='left', va='center')
ax.text(1, 0.45, '2001年', transform=ax.transAxes, size=46, ha='right')
细节修改
上面我们实现了2001年各个国家航空客运量(人数)前10名的可视化,现在我们把它封装成一个函数。
爆炸动画
刚才我们已经封装了(year)函数,现在只需要简单的调用模块,就可以沿着时间方向渲染成动画效果了。
import matplotlib.animation as animation
from IPython.display import HTML
fig, ax = plt.subplots(figsize=(15, 8))
animator = animation.FuncAnimation(fig, draw_barchart, frames=range(1970, 2016))
HTML(animator.to_jshtml())
动态排名图可以输出为视频文件,还可以在视频片段中加入自己喜欢的bgm,让整体效果更具爆发力。不过在输出视频之前,需要先安装,这里只是简单的说一下安装步骤:
命令行安装命令行输入brew以上安装步骤如有疑问请自行百度
animator.to_html5_video()
animator.save('countryflys.mp4')
所有代码
不到40行代码的超然动态排序图
%matplotlib inline
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import matplotlib.animation as animation
from IPython.display import HTML
#显示中文(可能还会显示不了,请自行百度解决中文问题)
plt.rcParams['font.sans-serif']=['SimHei']
def draw_barchart(year):
#整理数据
year = str(year)+'年'
df = pd.read_excel('国际数据主要国家(地区)年度数据.xls', skiprows=[0, 1, 2])
df2 = df[['地区', year]].sort_values(by=year, ascending=False).head(7)
df2.sort_values(by=year, ascending=True, inplace=True)
#横向条形图
ax.clear()
ax.barh(df2['地区'], df2[year], color=[countrycolors[country] for country in df2['地区']])
dx = df[year].max()/200
for i, (value, country) in enumerate(zip(df2[year], df2['地区'])):
ax.text(value-dx, i, country, size=14, weight=600, ha='right', va='bottom')
ax.text(value+dx, i, f'{value:,.0f}', size=14, ha='left', va='center')
#细节修饰
ax.text(1, 0.45, year, transform=ax.transAxes, color='#777777', size=46, ha='right', weight=800)
ax.text(0, 1.06, '各国航空客运量(人次)', transform=ax.transAxes, size=12, color='#777777')
ax.xaxis.set_ticks_position('top')
ax.tick_params(axis='x', colors='#777777', labelsize=12)
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.margins(0, 0.01)
ax.grid(which='major', axis='x', linestyle='-')
ax.set_axisbelow(True)
ax.text(0.3, 1.05, '1970~2015各国航空客运量(人次)',
transform=ax.transAxes, size=24, weight=600, ha='left')
plt.box(False)
fig, ax = plt.subplots(figsize=(15, 8))
animator = animation.FuncAnimation(fig, draw_barchart, frames=range(1970, 2016))
HTML(animator.to_jshtml())
代码获取方式请在【公众号:邓和他】后台回复关键词“动态排序图”。如果觉得有用,请转发支持