欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

python matplotlib绘制动态图

程序员文章站 2022-03-01 15:04:26
...

1. 效果

python matplotlib绘制动态图python matplotlib绘制动态图

 

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