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


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')感兴趣的读者如想获得详细信息可参考:https://matplotlib.org/3.1.1/api/animation_api.html。
原文链接:https://towardsdatascience.com/learn-how-to-create-animated-graphs-in-python-fce780421afe
本文转自:机器之心 公众号;
END
合作请加QQ:365242293??
数据分析(ID?:?ecshujufenxi?)互联网科技与数据圈自己的微信,也是WeMedia自媒体联盟成员之一,WeMedia联盟覆盖5000万人群。

关注公众号:拾黑(shiheibook)了解更多
[广告]赞助链接:
四季很好,只要有你,文娱排行榜:https://www.yaopaiming.com/
让资讯触达的更精准有趣:https://www.0xu.cn/
关注网络尖刀微信公众号随时掌握互联网精彩
赞助链接
排名
热点
搜索指数
- 1 中央经济工作会议在北京举行 7904038
- 2 水银体温计网上已“炒疯” 7808503
- 3 女子买千元羽绒服穿1天变吸油服 7712573
- 4 “九天”无人机成功首飞 7617951
- 5 灌面汤杀妻案一审宣判:凶手被判死缓 7520463
- 6 断码断货!这一款国货卖爆了 7423868
- 7 日本附近海域发生6.8级地震 7328187
- 8 直击北京初雪 7232762
- 9 村支书卖小米被小米法务投诉下架 7143661
- 10 寒潮来袭 “速冻”模式如何应对 7043263







数据分析
