python matplotlib绘制动态图

1. 效果

图片图片

 

2. 代码

import matplotlib.animation as ani
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

def load_data():
    """
    获取数据
    """
    url = "./time_series_covid19_deaths_global.csv"
    df_all = pd.read_csv(url, delimiter=',', header='infer')

    df_interest = df_all.loc[
        df_all['Country/Region'].isin(['United Kingdom', 'US', 'Italy', 'Germany'])
        & df_all['Province/State'].isna()]
    df_interest.rename(
    index=lambda x: df_interest.at[x, 'Country/Region'], inplace=True)
    
    df_transpose = df_interest.transpose()
    df_final = df_transpose.drop(['Province/State', 'Country/Region', 'Lat', 'Long'])
    df_final = df_final.loc[(df_final != 0).any(1)]

    df_final.index = pd.to_datetime(df_final.index)
    return df_final


def data_plot(df):
    """
    绘制曲线图
    """
    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(df.columns)
        p = plt.plot(df[:i].index, df[: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
    animator = ani.FuncAnimation(fig, buildmebarchart, interval = 1000)
    plt.show()

def data_plot2(data):
    """
    绘制饼状图
    """
    fig,ax = plt.subplots()
    explode=[0.01, 0.01, 0.01, 0.01] #pop out each slice from the piedef getmepie(i):
    
    def getmepie(i):
        def absolute_value(val): #turn % back to a number
            a  = np.round(val/100.*data.head(i).max().sum(), 0)
            return int(a)
        ax.clear()
        plot = data.head(i).max().plot.pie(y=data.columns, autopct=absolute_value, label='', explode = explode, shadow =False)
        plot.set_title('Total Number of Deaths\n' + str(data.index[min(i, len(data.index)-1)].strftime('%y-%m-%d')), fontsize=12)
    animator = ani.FuncAnimation(fig, getmepie, interval = 200)
    plt.show()


def data_plot3(data):
    fig = plt.figure()
    bar = 'vertical'
    def buildmebarchart(i=int):
        iv = min(i, len(data.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 = data.max().index
        y_pos = np.arange(len(objects))
        
        performance = data.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(data.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()
    
if __name__ == "__main__":
    """
    主函数
    """
    data = load_data()
    data_plot(data)
    data_plot2(data)
    data_plot3(data)

 

3. 数据

https://download.csdn.net/download/jingyi130705008/14920331

 

 

参考:

https://matplotlib.org/3.1.1/api/animation_api.html

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值