如何在Python中创建Gif动图?(动图数据可视化基础教学)
随着数据以前所未有的速度不断膨胀,数据分析师们往往被要求对数据进行分析并加以理解。一旦发生这种情况,就需要更加有效的方式来传达数据。
然而,传达数据分析的结果往往十分棘手。为了更有效地交流,数据可视化是一种流行且非常有效的技巧。
把世界上所有没有经过处理的数据掌握在我们手里并不能让交流变得容易,反而会变得更加困难--Cole Nussbaumer Knaflic
为了更加方便我们的交流,数据可视化至关重要。动图数据可视化可以以更形象、更直观的形式把数据呈现给他人看。
在本文中,我们将一步步学习如何制作图表数据的动图可视化,学习如何把数据可视化成线条图、条形图和饼状图。
动画是如何生成的?
在典型的方式中,正如你在Python中所期望的那样,存在一个非常易于使用的包,它使我们能够为数据可视化添加额外的维度。
该包是 FuncAnimation 扩展方法,是 Python matplotlib 库中 Animation 类的一部分。我们将讨论如何使用它的多个示例,你可以将此函数看作一个while循环,它将不断在画布上重新绘制我们的图形。
1.如何使用数据库?
数据动图可视化从接入数据库开始:
import matplotlib.animation as ani
animator = ani.FuncAnimation(fig, chartfunc, interval = 100)
让我们仔细看看FuncAnimation如何输入:
- fig 是我们用来“绘制我们的图形”的图形对象
- chartfunc 是一个接受数字输入的函数,它表示时间序列上的时间(随着数字的增加,我们沿着时间线移动)
- interval 是帧之间的延迟(毫秒),默认为200。
我们需要做的就是把它们的图形参数化为一个函数,这个函数把时间序列中的点作为输入,这就是动图化的开始!
入门
如果你对数据可视化基础知识不太了解,建议点击下面的链接来仔细学习相关内容:
接下来,我们将使用来自新冠肺炎的数据,并使用下面代码给出的最终数据集。
import matplotlib.animation as ani
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
url = '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)
动态线条图
我们需要做的第一件事是定义图的各项,这些项将保持不变。 也就是说,创建图形对象,x和y标签,设置线条颜色和图形边距。
import numpy as np
import matplotlib.pyplot as plt
color = ['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 curve
import matplotlib.animation as ani
animator = ani.FuncAnimation(fig, buildmebarchart, interval = 100)
plt.show()
动态饼状图
代码结构看起来与线图的结构相同。但是,这里面还是会有一些区别。
import numpy as np
import matplotlib.pyplot as plt
fig,ax = plt.subplots()
explode=[0.01,0.01,0.01,0.01] #pop out each slice from the pie
def 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()
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')
以上为本次如何利用Python来实现动图数据可视化的基础教程,动手才能成长,快拿去练手吧~记得关注、转发+收藏。
--END--
欢迎大家关注我们的公众号:为AI呐喊(weainahan)