首页 > 技术文章 > python数据可视化:动态条形图展现中国贫困县脱贫过程

ljy1227476113 2021-01-30 22:21 原文

import xlrd
import random
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.animation as animation

def random_color():#返回随机颜色
    colorArr = ['1','2','3','4','5','6','7','8','9','A','B','C','D','E','F']
    color = ""
    for i in range(6):
        color += colorArr[random.randint(0,14)]
    return "#"+color

def trad_read_excel_data():#点对点读取excel数据
    data=xlrd.open_workbook(r"中国扶贫数据.xlsx")
    sheet=data.sheet_by_name("Sheet1")
    data=[]
    for r in range(sheet.nrows):
        mid_data=[]
        for c in range(sheet.ncols):
            mid_data.append(sheet.cell_value(r,c))
        data.append(list(mid_data))
    for item in data:
        print(item)

def dynamic_bar():#动态条形图
    excel=pd.read_excel(r'中国扶贫数据.xlsx',sheet_name='Sheet3')#读取数据
    province_data=excel[:22]
    dates=province_data.index.tolist()
    countries=province_data.columns.tolist()[1:]
    values=province_data.values.tolist()
    # for value in values:
    #     value.pop(0)
    # print(countries)
    # print(values)
    color=[]
    for i,j in enumerate(countries):
        color.append([j, random_color()])
    colors=dict(color)

    plt.rcParams['font.sans-serif'] = ['SimHei']
    fig, ax = plt.subplots(figsize=(15, 8))#新建图像
    ax.clear()#清空图像
    plt.gca().invert_yaxis()#水平y轴
    plt.tick_params(direction="in")#刻度朝里
    plt.box(False)#去除边框
    plt.xticks([])#去除x轴刻度值

    def draw_barchart(num):#动态更新函数
        ax.clear()
        c=sorted(zip(values[num][1:],countries),reverse=False)#zip排序,使得最大值始终在前
        a=[i for i,j in c]#排序后的values,数量值
        b=[j for i,j in c]#排序后的countries,省份
        ax.set_xlim(right=max(a))#设置x轴最大值为values[num]中的最大值
        ax.xaxis.set_ticks_position('top')#x轴放在顶部
        ax.margins(0, 0.01)
        ax.grid(which='major', axis='x', linestyle='-')
        ax.set_axisbelow(True)
        ax.text(0, 1.08,'中国脱贫县脱贫进度',transform=ax.transAxes,size=24,weight=600,ha='left')#标题
        ax.text(0,1.04,'数据来源:中国减贫研究数据库',transform=ax.transAxes,size=12,color='#777777')#副标题
        ax.text(1,0.4,values[num][0], transform=ax.transAxes, size=46, ha='right')#日期值
        ax.barh(b,a,color=[colors[x] for x in b])#更新条形图
        plt.xticks([])#去除x轴刻度值
        for i, (value, country) in enumerate(zip(a,b)):
            if value==0:continue#为0不显示文本
            ax.text(value,i,country,ha='right',color='black')#每条形的文字
            ax.text(value,i,value,size=14,ha='left',va='center')#每条形的数字

    animator=animation.FuncAnimation(fig,draw_barchart,frames=[i for i in range(len(values))],interval=10,repeat=False)
    # plt.show()
    animator.save('中国脱贫县脱贫进度.gif', writer='imagemagick')

dynamic_bar()

数据来源:中国减贫研究数据库

excel文件格式为

 

 

如果需要代换,更换数据及相应说明即可

 

推荐阅读