python柱形图代码_数据可视化之制柱形竞赛图

我们经常看到的Bar Chart Race(柱形竞赛图),可以看到数据的呈现非常的直观。今天就一起来学习下如何生成和上面一样的柱形竞赛图。

Bar-Chart-Race.gif

1、导入Python库

import pandas as pd

import matplotlib.pyplot as plt

import matplotlib.ticker as ticker

import matplotlib.animation as animation

from IPython.display import HTML

2、加载数据集

这里使用的是城市人口数据集,加载我们想要的数据:其中,name为城市名称,group为城市所在区域。

df = pd.read_csv("data/city_populations.csv", usecols=['name', 'group', 'year', 'value'])

df.head()

df.png

3、初步处理数据

提取某一年的TOP10城市:

current_year = 2018

dff = df[df['year'].eq(current_year)].sort_values(by='value', ascending=True).head(10)

dff.png

4、 绘制基础柱状图

fig, ax = plt.subplots(figsize=(15, 8))

ax.barh(dff['name'], dff['value'])

barh.png

5、 调整样式(设置颜色、添加标签)重新绘制图片

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))

# pass colors values to `color=`

ax.barh(dff['name'], dff['value'], color=[colors[group_lk[x]] for x in dff['name']])

# iterate over the values to plot labels and values (Tokyo, Asia, 38194.2)

for i, (value, name) in enumerate(zip(dff['value'], dff['name'])):

ax.text(value, i, name, ha='right') # Tokyo: name

ax.text(value, i-.25, group_lk[name], ha='right') # Asia: group name

ax.text(value, i, value, ha='left') # 38194.2: value

# Add year right middle portion of canvas

ax.text(1, 0.4, current_year, transform=ax.transAxes, size=46, ha='right')

bar-2018.png

6、 完善代码,将代码整合进函数

优化内容:

文字:更新字体大小,颜色,方向

轴:将X轴移到顶部,添加颜色和字幕

网格:在条后面添加线

格式:逗号分隔的值和坐标轴

添加标题,字幕,装订线空间

删除:框框,y轴标签

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.12, 'The most populous cities in the world from 1500 to 2018',

transform=ax.transAxes, size=24, weight=600, ha='left')

ax.text(1, 0, 'by @pratapvardhan; credit @jburnmurdoch', transform=ax.transAxes, ha='right',

color='#777777', bbox=dict(facecolor='white', alpha=0.8, edgecolor='white'))

plt.box(False)

draw_barchart(2018)

bar-new.png

7、 绘制动态柱状图

为了看起来像是在竞赛,我们使用matplotlib.animation中的FuncAnimation来重复调用上面的函数在画布上制作动画。frames参数为函数接受的值。

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(1968, 2019))

HTML(animator.to_jshtml())

# or use animator.to_html5_video() or animator.save()

8、 额外奖励,绘制xkcd风格的图形

with plt.xkcd():

fig, ax = plt.subplots(figsize=(15, 8))

draw_barchart(2018)

xkcd.png

matplotlib 的 animations使用说明

Matplotlib中动画实现的原理跟其它一样,就是让多幅图连续播放,每一幅图叫做一帧(frame)。

生成动画的核心语句如下:

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(1968, 2019))

HTML(animator.to_jshtml())

# or use animator.to_html5_video() or animator.save()

class matplotlib.animation.FuncAnimation(fig, func, frames=None, init_func=None, fargs=None, save_count=None, *, cache_frame_data=True, **kwargs)

参数说明:

fig:进行动画绘制的figure

func:更新函数

frames:传入更新函数的迭代值,即生成每一帧(frame)的参数

init_func:初始函数

fargs:传入更新函数的额外参数

save_count:指定保存动画(gif或mp4)的帧数

interval:指定帧间隔时间,单位是ms

repeat_delay:如果指定了循环动画,则设置每次循环的间隔时间

repeat:指定是否循环动画

blit:是否优化绘图

cache_frame_data:控制是否缓存帧数据

核心方法说明:

save(self, filename[, writer, fps, dpi, …]):将动画保存为文件(gif或mp4).

to_html5_video(self[, embed_limit]):将动画HTML5动画

to_jshtml(self[, fps, embed_frames, …]):将动画返回为HTML格式

参考链接:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值