让数据“动”起来:Python动态图表制作!
杰哥的IT之旅
共 8810字,需浏览 18分钟
·
2020-12-06 18:32
来源:机器之心
原文链接:https://towardsdatascience.com/learn-how-to-create-animated-graphs-in-python-fce780421afe
import matplotlib.animation as ani
animator = ani.FuncAnimation(fig, chartfunc, interval = 100)
fig 是用来 「绘制图表」的 figure 对象;
chartfunc 是一个以数字为输入的函数,其含义为时间序列上的时间;
interval 这个更好理解,是帧之间的间隔延迟,以毫秒为单位,默认值为 200。
import matplotlib.animation as ani
import matplotlib.pyplot as plt
import numpy as np
import pandas as pdurl = 'https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_deaths_global.csv'
df = pd.read_csv(url, delimiter=',', header='infer')df_interest = df.loc[
df['Country/Region'].isin(['United Kingdom', 'US', 'Italy', 'Germany'])
& df['Province/State'].isna()]df_interest.rename(
index=lambda x: df_interest.at[x, 'Country/Region'], inplace=True)
df1 = df_interest.transpose()df1 = df1.drop(['Province/State', 'Country/Region', 'Lat', 'Long'])
df1 = df1.loc[(df1 != 0).any(1)]
df1.index = pd.to_datetime(df1.index)
import numpy as np
import matplotlib.pyplot as pltcolor = ['red', 'green', 'blue', 'orange']
fig = plt.figure()
plt.xticks(rotation=45, ha="right", rotation_mode="anchor") #rotate the x-axis values
plt.subplots_adjust(bottom = 0.2, top = 0.9) #ensuring the dates (on the x-axis) fit in the screen
plt.ylabel('No of Deaths')
plt.xlabel('Dates')
def buildmebarchart(i=int):
plt.legend(df1.columns)
p = plt.plot(df1[:i].index, df1[:i].values) #note it only returns the dataset, up to the point i
for i in range(0,4):
p[i].set_color(color[i]) #set the colour of each curveimport matplotlib.animation as ani
animator = ani.FuncAnimation(fig, buildmebarchart, interval = 100)
plt.show()
import numpy as np
import matplotlib.pyplot as pltfig,ax = plt.subplots()
explode=[0.01,0.01,0.01,0.01] #pop out each slice from the piedef getmepie(i):
def absolute_value(val): #turn % back to a number
a = np.round(val/100.*df1.head(i).max().sum(), 0)
return int(a)
ax.clear()
plot = df1.head(i).max().plot.pie(y=df1.columns,autopct=absolute_value, label='',explode = explode, shadow = True)
plot.set_title('Total Number of Deaths\n' + str(df1.index[min( i, len(df1.index)-1 )].strftime('%y-%m-%d')), fontsize=12)import matplotlib.animation as ani
animator = ani.FuncAnimation(fig, getmepie, interval = 200)
plt.show()
df1.head(i).max()
fig = plt.figure()
bar = ''def buildmebarchart(i=int):
iv = min(i, len(df1.index)-1) #the loop iterates an extra one time, which causes the dataframes to go out of bounds. This was the easiest (most lazy) way to solve this :)
objects = df1.max().index
y_pos = np.arange(len(objects))
performance = df1.iloc[[iv]].values.tolist()[0]
if bar == 'vertical':
plt.bar(y_pos, performance, align='center', color=['red', 'green', 'blue', 'orange'])
plt.xticks(y_pos, objects)
plt.ylabel('Deaths')
plt.xlabel('Countries')
plt.title('Deaths per Country \n' + str(df1.index[iv].strftime('%y-%m-%d')))
else:
plt.barh(y_pos, performance, align='center', color=['red', 'green', 'blue', 'orange'])
plt.yticks(y_pos, objects)
plt.xlabel('Deaths')
plt.ylabel('Countries')animator = ani.FuncAnimation(fig, buildmebarchart, interval=100)plt.show()
animator.save(r'C:\temp\myfirstAnimation.gif')
如果您觉得这篇文章对您有点用的话,麻烦您为本文来个四连:转发分享、点赞、点在看、留言,因为这将是我写作与分享更多优质文章的最强动力!
本公众号全部博文已整理成一个目录,请在公众号后台回复「m
」获取!
推荐阅读:
1、花费一周整理的Python资源,让我学习效率,事半功倍!
2、超全!我把 Python 的 200 个标准库整理出来了!
3、40000字 Matplotlib 实操干货,真的全!
4、为了探究妹纸对内衣的喜好,我爬了淘宝内衣店的数据!
5、任意爬取!超全开源爬虫工具箱
6、11 种方法教你用 Python 高效下载资源!
推荐阅读:
2、超全!我把 Python 的 200 个标准库整理出来了!
3、40000字 Matplotlib 实操干货,真的全!
4、为了探究妹纸对内衣的喜好,我爬了淘宝内衣店的数据!
5、任意爬取!超全开源爬虫工具箱
6、11 种方法教你用 Python 高效下载资源!
点个[在看],是对杰哥最大的支持!
评论