用matplotlib中的FuncAnimation()实现GDP世界排名动态图

很久以前写过一篇使用Matplotlib实现GDP世界排名动态图,具体可以参考:用Matplotlib实现世界GDP动态排名_Sun_Sherry的博客-CSDN博客_matplotlib绘制与滚动排行榜。但当时的动态图是用286张常规的水平条形图压缩而成了,实现起来稍微有些复杂,这篇博客则考虑直接使用maplotlib中的动态图函数FuncAnimation()重新实现制作一遍。数据集可以在原博文给出的网盘链接中下载。

具体代码如下:

import pandas as pd
import matplotlib as mpl
from matplotlib import cm
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker 
import matplotlib.animation as animation
from IPython.display import HTML
from datetime import datetime
from matplotlib import cm
plt.rcParams['font.sans-serif'] = ['SimHei']  
plt.rcParams['axes.unicode_minus'] = False  
plt.rc('axes',axisbelow=True) 
mpl.rcParams['animation.embed_limit'] = 2**128

df=pd.read_csv(r'C:/Users/Desktop/main_country.csv',index_col=1)#改成自己的地址

for year in range(1960,2018):
    df[str(year)+'_rank']=11-df[str(year)].rank(ascending=False)
    
def draw_gdp(frame):
    ax.clear()
    left_year=1960+frame//10
    if frame<570:
        right_year=left_year+1
        step=frame%10
        rank_val=(df[str(right_year)+"_rank"]-df[str(left_year)+'_rank'])/10*step+df[str(left_year)+'_rank']
        gdp_val=(df[str(right_year)]-df[str(left_year)])/10*step+df[str(left_year)]
    else:
        rank_val=df[str(left_year)+"_rank"]
        gdp_val=df[str(left_year)]
    colors=cm.Spectral_r(gdp_val.values/gdp_val.max())
    gdp_val=gdp_val/1e11
    bars=ax.barh(rank_val.values,gdp_val.values,height=0.5,color=colors)
    ax.set_ylim(-0.6,10.6)
    ax.spines['top'].set_color('none')   # 设置上‘脊梁’为无色
    ax.spines['right'].set_color('none')
    rank_val=rank_val[(rank_val>=0)&(rank_val<11)]
    label=rank_val.index
    val=rank_val.values
    label=rank_val.index
    ax.set_yticks(val)
    ax.set_yticklabels(label)
    ax.text(0.8*ax.get_xlim()[1],1,str(left_year)+"年",fontsize=20)
    ax.set_title("1960-2017年世界GDP动态排名图(单位:百亿$)")
    for bar in bars:
        if bar.get_y()>0:
            width=bar.get_width()
            plt.text(width+ax.get_xlim()[1]*0.02,bar.get_y()+0.125,"{:.2f}".format(width))
    
fig,ax=plt.subplots(figsize=(6,4),dpi=100)
plt.subplots_adjust(left=0.12, right=0.98, top=0.85, bottom=0.1,hspace=0,wspace=0)  
animator=animation.FuncAnimation(fig,draw_gdp,np.arange(0,571,1),interval=100)
animator.save('gdp.gif',writer='pillow',savefig_kwargs={'facecolor':'white'},fps=10)
plt.show()

其结果如下:

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
使用 Matplotlib 实现动态折线图可以通过以下步骤实现: 1. 导入必要的库,如 Matplotlib 和 NumPy。 ```python import matplotlib.pyplot as plt import numpy as np ``` 2. 创建一个 Figure 对象和一个 Axes 对象,并设置一些基本参数。 ```python fig, ax = plt.subplots() ax.set_xlim(0, 10) ax.set_ylim(0, 10) line, = ax.plot([], []) ``` 3. 定义一个函数,用于更新数据和折线图。该函数接受一个参数表示当前时间,根据时间生成一些随机数据,并更新折线图。 ```python def update(t): x = np.linspace(0, 10, 100) y = np.sin(x - t) + np.random.normal(0, 0.1, size=(100,)) line.set_data(x, y) ``` 4. 使用 FuncAnimation 函数创建一个动画对象,并指定更新函数和帧数。 ```python from matplotlib.animation import FuncAnimation ani = FuncAnimation(fig, update, frames=np.linspace(0, 10, 100), interval=50) ``` 5. 调用 plt.show() 函数显示动态折线图。 ```python plt.show() ``` 完整的代码如下所示: ```python import matplotlib.pyplot as plt import numpy as np from matplotlib.animation import FuncAnimation fig, ax = plt.subplots() ax.set_xlim(0, 10) ax.set_ylim(-2, 2) line, = ax.plot([], []) def update(t): x = np.linspace(0, 10, 100) y = np.sin(x - t) + np.random.normal(0, 0.1, size=(100,)) line.set_data(x, y) ani = FuncAnimation(fig, update, frames=np.linspace(0, 10, 100), interval=50) plt.show() ``` 该代码会生成一个动态折线图,每隔 50 毫秒更新一次,总共更新 100 帧,折线的形状会随着时间变化而变化。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值