超燃焼動的可視化ストライプ図のソースコードと効果図


くだらないことを言わないで、直接コードをつけます:
import pandas as pd
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

import matplotlib.colors as mc
import colorsys
from random import randint
import matplotlib.animation as animation
from IPython.core.display import HTML
import re
import pdb
df = pd.read_csv('shares/data/World 1960-2016GDP1.csv',encoding = "gbk",usecols=['country','year','value'])


df= df[df['year']>1980].copy()
#        ,         
#        
#     https://blog.csdn.net/cxd3341/article/details/105016903
df = df.pivot(index='country',columns='year',values='value')
df = df.reset_index()

次の図は、データ補間コードです.
for p in range(3):
    i=0
    while i

国ごとにランダムに棒グラフの色を設定します.
def transform_color(color, amount = 0.5):

    try:
        c = mc.cnames[color]
    except:
        c = color
        c = colorsys.rgb_to_hls(*mc.to_rgb(c))
    return colorsys.hls_to_rgb(c[0], 1 - amount * (1 - c[1]), c[2])

all_names = df['country'].unique().tolist()
random_hex_colors = []
for i in range(len(all_names)):
    random_hex_colors.append('#' + '%06X' % randint(0, 0xFFFFFF))

rgb_colors = [transform_color(i, 1) for i in random_hex_colors]
rgb_colors_opacity = [rgb_colors[x] + (1.0,) for x in range(len(rgb_colors))]
rgb_colors_dark = [transform_color(i, 1.0) for i in random_hex_colors]

 
number_of_element = 8
plt.rcParams['font.sans-serif']=['SimHei']
plt.rcParams['animation.ffmpeg_path'] ='C:/Program Files/ffmpeg-win64-static/bin/ffmpeg.exe'
fig, ax = plt.subplots(figsize=(15,9))

def draw_barchart(year):
    dff = df[df['year'].eq(year)].sort_values(by='value',ascending=True).tail(number_of_element)
    ax.clear()
    normal_colors = dict(zip(df['country'].unique(),rgb_colors_opacity))
    dark_colors = dict(zip(df['country'].unique(),rgb_colors_dark))
    
    ax.barh(dff['country'],dff['value'],color=[normal_colors[x] for x in dff['country']],height=0.4,
           edgecolor = ([dark_colors[x] for x in dff['country']]),linewidth='2')
    
    dx = dff['value'].max()/200
 
    for i, (value, country) in enumerate(zip(dff['value'],dff['country'])):
        ax.text(value + dx, i,  country,          size=14,weight=600,    ha='right',va='center')   #Tokyo: name
        ax.text(value + dx, i,     f'{value:,.0f}',size=14, ha='left',va='center')    #38194.2: value
    
        #ax.text(value + dx, i + (num_of_elements / 50), '    ' + name,
        #size = 36, weight = 'bold', ha = 'left', va = 'center', fontdict = {'fontname': 'Trebuchet MS'})
        #ax.text(value + dx, i - (num_of_elements / 50), f'    {value:,.0f}', size = 36, ha = 'left', va = 'center')
    #    
    #              
    year_unit_displayed = re.sub(r'\^(.*)', r'', str(year))
    ax.text(1.0,0.4, year_unit_displayed, transform=ax.transAxes, size=46,ha='right')
    ax.text(0,1.06,'GDP(   )',transform=ax.transAxes,size=12,color='#777777')
    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([])
    ax.margins(0,0.01)
    ax.grid(which='major',axis='x',linestyle='-')
    ax.set_axisbelow(True)
    ax.text(0,1.12,'The GDP of each Country from 1981 to 2016',
           transform=ax.transAxes,size=24,weight=600,ha='left')
    ax.text(1.3,0,'by@ Poseidon;',transform=ax.transAxes,size = 20,
           ha='right',color='#777777',bbox=dict(facecolor='white',alpha=0.4,
                                               edgecolor='white'))
    plt.locator_params(axis = 'x', nbins = 4)
    plt.box(False)
    plt.subplots_adjust(left = 0.075, right = 0.75, top = 0.825, bottom = 0.05, wspace = 0.2, hspace = 0.2)
    

animator = animation.FuncAnimation(fig,draw_barchart,frames=frames_list)

HTML(animator.to_jshtml())
FFwriter=animation.FFMpegWriter(fps=10, extra_args=['-vcodec', 'libx264'])
animator.save("shares/data/WorldGDP.mp4", writer = FFwriter)

 
超燃焼動的可視化ストライプ図