使用Python绘制柱形竞赛图

您所在的位置:网站首页 python绘制条形图代码 使用Python绘制柱形竞赛图

使用Python绘制柱形竞赛图

2024-07-07 15:53| 来源: 网络整理| 查看: 265

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

在这里插入图片描述

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

在这里插入图片描述

3、初步处理数据

提取某一年的TOP10城市:

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

4、 绘制基础柱状图

fig, ax = plt.subplots(figsize=(15, 8)) ax.barh(dff['name'], dff['value'])

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

''' 遇到问题没人解答?小编创建了一个Python学习交流QQ群:579817333 寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书! ''' 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')

在这里插入图片描述

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)

在这里插入图片描述

7、 绘制动态柱状图

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

''' 遇到问题没人解答?小编创建了一个Python学习交流QQ群:579817333 寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书! ''' 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)

原文地址:https://towardsdatascience.com/bar-chart-race-in-python-with-matplotlib-8e687a5c8a41

matplotlib 的 animations使用说明

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

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

''' 遇到问题没人解答?小编创建了一个Python学习交流QQ群:579817333 寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书! ''' 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()

核心函数是animation.FuncAnimation(),接下来一起学习下如何使用此函数。

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

参数说明:

fig:进行动画绘制的figurefunc:更新函数frames:传入更新函数的迭代值,即生成每一帧(frame)的参数init_func:初始函数fargs:传入更新函数的额外参数save_count:指定保存动画(gif或mp4)的帧数interval:指定帧间隔时间,单位是msrepeat_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格式


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3