# 火爆全网的条形竞赛图，Python轻松实现

2022年01月16日 阅读数：3

## 纯matplotlib实现

matplotlib实现bar-chart-race很简单，直接上代码服务器

``````import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import matplotlib.animation as animation
from IPython.display import HTML
url = 'https://gist.githubusercontent.com/johnburnmurdoch/4199dbe55095c3e13de8d5b2e5e5307a/raw/fa018b25c24b7b5f47fd0568937ff6c04e384786/city_populations'
df = pd.read_csv(url, 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(current_year):
dff = df[df['year'].eq(current_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')
ax.text(1, 0.4, current_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.15, 'The most populous cities in the world from 1500 to 2018',
transform=ax.transAxes, size=24, weight=600, ha='left', va='top')
ax.text(1, 0, 'by @pratapvardhan; credit @jburnmurdoch', transform=ax.transAxes, color='#777777', ha='right',
bbox=dict(facecolor='white', alpha=0.8, edgecolor='white'))
plt.box(False)

fig, ax = plt.subplots(figsize=(15, 8))
animator = animation.FuncAnimation(fig, draw_barchart, frames=range(1900, 2019))
HTML(animator.to_jshtml())
``````

## xkcd手绘风格

``````with plt.xkcd():
fig, ax = plt.subplots(figsize=(15, 8))
animator = animation.FuncAnimation(fig, draw_barchart, frames=range(1900, 2019))
HTML(animator.to_jshtml())
``````

## bar_chart_race库极简实现

GitHub地址：https://github.com/dexplo/bar_chart_raceide

``````git clone https://github.com/dexplo/bar_chart_race
``````

``````import bar_chart_race as bcr
# 获取数据
# 生成GIF图像
bcr.bar_chart_race(df, 'covid19_horiz.gif')
``````

``````bcr.bar_chart_race(
df=df,
filename='covid19_horiz.mp4',
orientation='h',
sort='desc',
n_bars=6,
fixed_order=False,
fixed_max=True,
steps_per_period=10,
interpolate_period=False,
label_bars=True,
bar_size=.95,
period_label={'x': .99, 'y': .25, 'ha': 'right', 'va': 'center'},
period_fmt='%B %d, %Y',
period_summary_func=lambda v, r: {'x': .99, 'y': .18,
's': f'Total deaths: {v.nlargest(6).sum():,.0f}',
'ha': 'right', 'size': 8, 'family': 'Courier New'},
perpendicular_bar_func='median',
period_length=500,
figsize=(5, 3),
dpi=144,
cmap='dark12',
title='COVID-19 Deaths by Country',
title_size='',
bar_label_size=7,
tick_label_size=7,
shared_fontdict={'family' : 'Helvetica', 'color' : '.1'},
scale='linear',
writer=None,
fig=None,
bar_kwargs={'alpha': .7},
filter_column_colors=False)
``````

## streamlit+bar_chart_race

streamlit是我最近特别喜欢玩的一个机器学习应用开发框架，它能帮你不用懂得复杂的HTML,CSS等前端技术就能快速作出来一个炫酷的Web APP。

``````from bar_chart_race import bar_chart_race as bcr
import pandas as pd
import streamlit as st
import streamlit.components.v1 as components

st.title('Bar Chart Race', anchor=None)

df = df.set_index("date")