使用Python画动态条形图

原始数据:
使用Python画动态条形图_第1张图片
为了之后方便处理,我们把date改成year一下:
使用Python画动态条形图_第2张图片

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import random
import matplotlib.animation as animation
from IPython.core.display import HTML



df = pd.read_excel('test.xls')
name_list = list(set(df.name))


#导入random函数,randomcolor用于生成颜色代码
# randomcolor生成颜色代码原理,
# 【1-9/A-F】15个数字随机组合成6位字符串前面再加上一个“#”号键
import random
def randomcolor():
    colorlist = ['1','2','3','4','5','6','7','8','9','A','B','C','D','E','F']
    color =''
    for i in range(6):
        color += random.choice(colorlist)
    return '#'+ color


# 构造一个name_color字典
name_color = {}
for name in name_list:
    name_color[name] = randomcolor()


#定义一个画条形图的函数:
def draw_barchart(current_year):
    dff = df[df['year'].eq(current_year)].sort_values(by='fan_num',ascending = True).tail(8)

    ax.clear()
    ax.barh(dff['name'],dff['fan_num'],color = [name_color[x] for x in dff['name']]) #ax.bar是一般的条形图,barh是水平的条形图,h是horizontal的意思
    dx = dff['fan_num'].max()/200
    for i ,(value,name) in enumerate(zip(dff['fan_num'], dff['name'])):
            ax.text(value+dx,i ,f'{value:,.0f}',size = 14,ha = 'left',va ='center')
    ax.text(1,0.4,current_year,transform = ax.transAxes,color ='#777777',size = 46,ha ='right',weight=800) 
    ax.text(0,1.06,'人',transform = ax.transAxes,size=12,color='#777777')

        #set_major_formatter表示刻度尺格式;
    ax.xaxis.set_major_formatter(ticker.StrMethodFormatter('{x:,.0f}'))
    ax.xaxis.set_ticks_position('top')
    ax.tick_params(axis='x',colors='#777777',labelsize=12)
    # ax.set_yticks([]) #set_yticks([])表示不显示y轴的取值
        #margins表示自动缩放余额;
    ax.margins(0,0.01)
        # 设置后面的网格
    ax.grid(which='major',axis='x',linestyle='-')
        #刻度线和网格线是在图标上方还是下方,True为下方
    ax.set_axisbelow(True)
    ax.text(0,1.15,'每日活跃粉丝人数',
            transform=ax.transAxes,size=24,weight=600,ha='left',va='top')
    ax.text(1,0,'by 小陈',transform = ax.transAxes,color ='#777777',ha = 'right',
               bbox = dict(facecolor='white',alpha = 0.8,edgecolor='white'))
        #取消图表周围的方框显示
    plt.box(False)


plt.rcParams['font.sans-serif'] = ['Microsoft YaHei'] #设置汉字字体
fig, ax = plt.subplots(figsize=(15, 8))#设置画布大小
animator = animation.FuncAnimation(fig, draw_barchart, frames=range(2014, 2020),interval=500) #interval越大速度越慢  
#保存到jshtml
HTML(animator.to_jshtml())

结果如下:
使用Python画动态条形图_第3张图片

当然,也可以不使用Python,目前很多网站都能实现这一目标,以下就是我在某网站上制作的动态条形图:

你可能感兴趣的:(Python零碎知识点)