Python中一种简单的动态图表制作方法

在读技术博客的过程中,我们会发现那些能够把知识、成果讲透的博主很多都会做动态图表 。他们的图是怎么做的?难度大吗?这篇文章就介绍了Python中一种简单的动态图表制作方法 。

Python中一种简单的动态图表制作方法

文章插图
如下所示,首先需要做的第一件事是定义图的各项,这些基础项设定之后就会保持不变 。它们包括:创建figure对象,x标和y标,设置线条颜色和figure边距等:
importnumpyasnpimportmatplotlib.pyplotaspltcolor=['red','green','blue','orange']fig=plt.figure()plt.xticks(rotation=45,ha="right",rotation_mode="anchor")#rotatethex-axisvaluesplt.subplots_adjust(bottom=0.2,top=0.9)#ensuringthedates(onthex-axis)fitinthescreenplt.ylabel('NoofDeaths')plt.xlabel('Dates')接下来设置curve函数,进而使用.FuncAnimation让它动起来:defbuildmebarchart(i=int):plt.legend(df1.columns)p=plt.plot(df1[:i].index,df1[:i].values)#noteitonlyreturnsthedataset,uptothepointiforiinrange(0,4):p[i].set_color(color[i])#setthecolourofeachcurveimportmatplotlib.animationasanianimator=ani.FuncAnimation(fig,buildmebarchart,interval=100)plt.show()动态饼状图

Python中一种简单的动态图表制作方法
文章插图
可以观察到,其代码结构看起来与线型图并无太大差异,但依旧有细小的差别 。
importnumpyasnpimportmatplotlib.pyplotaspltfig,ax=plt.subplots()explode=[0.01,0.01,0.01,0.01]#popouteachslicefromthepiedefgetmepie(i):defabsolute_value(val):#turn%backtoanumbera=np.round(val/100.*df1.head(i).max().sum(),0)returnint(a)ax.clear()plot=df1.head(i).max().plot.pie(y=df1.columns,autopct=absolute_value,label='',explode=explode,shadow=True)plot.set_title('TotalNumberofDeaths'+str(df1.index[min(i,len(df1.index)-1)].strftime('%y-%m-%d')),fontsize=12)importmatplotlib.animationasanianimator=ani.FuncAnimation(fig,getmepie,interval=200)plt.show()主要区别在于,动态饼状图的代码每次循环都会返回一组数值,但在线型图中返回的是我们所在点之前的整个时间序列 。返回时间序列通过df1.head(i)来实现,而.max()则保证了我们仅获得最新的数据,因为流行病导致死亡的总数只有两种变化:维持现有数量或持续上升 。df1.head(i).max()动态条形图
Python中一种简单的动态图表制作方法
文章插图
创建动态条形图的难度与上述两个案例并无太大差别 。在这个案例中,作者定义了水平和垂直两种条形图,读者可以根据自己的实际需求来选择图表类型并定义变量栏 。fig=plt.figure()bar=''defbuildmebarchart(i=int):iv=min(i,len(df1.index)-1)#theloopiteratesanextraonetime,whichcausesthedataframestogooutofbounds.Thiswastheeasiest(mostlazy)waytosolvethis:)objects=df1.max().indexy_pos=np.arange(len(objects))performance=df1.iloc[[iv]].values.tolist()[0]ifbar=='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('DeathsperCountry'+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:empmyfirstAnimation.gif')责任编辑:lq
【Python中一种简单的动态图表制作方法】
.dfma {position: relative;width: 1000px;margin: 0 auto;}.dfma a::after {position: absolute;left: 0;bottom: 0;width: 30px;line-height: 1.4;text-align: center;background-color: rgba(0, 0, 0, .5);color: #fff;font-size: 12px;content: "广告";}.dfma img {display: block;}
Python中一种简单的动态图表制作方法
文章插图

    推荐阅读