#导入工具包
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import matplotlib.animation as animation
#from IPython.display import HTML
import random
df = pd.read_csv('china_provincedata.csv', usecols=['provinceName', 'provinceShortName', 'dateId', 'confirmedCount'])
fig, ax = plt.subplots(figsize=(15, 8))
colors = dict(zip(
['India','Europe','Asia','Latin America','Middle East','North America','Africa'],
['#adb0ff', '#ffb3ff', '#90d595', '#e48381', '#aafbff', '#f7bb5f', '#eafb50']
))
group_lk = df.set_index('provinceName')['provinceShortName'].to_dict()
def draw_barchart(current_day):
dff = df[df['dateId'].eq(current_day)].sort_values(by='confirmedCount', ascending=True).tail(10)
ax.clear()
#ax.barh(dff['provinceName'], dff['confirmedCount'], color=[colors[group_lk[x]] for x in dff['provinceName']])
ax.barh(dff['provinceShortName'],dff['confirmedCount'],color = [get_colordict()[x] for x in dff['provinceShortName']])
dx = dff['confirmedCount'].max() / 200
for i, (value, name) in enumerate(zip(dff['confirmedCount'], dff['provinceName'])):
ax.text(value-dx, i, name, size=14, weight=600, ha='right', va='bottom')
ax.text(value-dx, i-.25, group_lk[name], size=10, color='#444444', ha='right', va='baseline')
ax.text(value+dx, i, f'{value:,.0f}', size=14, ha='left', va='center')
# ... 优化风格
ax.text(1, 0.4, current_day, transform=ax.transAxes, color='#777777', size=46, ha='right', weight=800)
ax.text(0, 1.06, 'Population (thousands)', 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 most populous cities in the world from 1500 to 2018',
transform=ax.transAxes, size=24, weight=600, ha='left')
ax.text(1, 0, 'by @pratapvardhan; credit @jburnmurdoch', transform=ax.transAxes, ha='right',
color='#777777', bbox=dict(facecolor='white', alpha=0.8, edgecolor='white'))
plt.box(False)
month_day=[0,31,29,31,30,31,30]
def all_day(start,end):
days = []
cur_day = start
while cur_day < end:
mon = (cur_day//100) % 100
if cur_day % 100 == month_day[mon]:
cur_day = 20200000+(mon+1)*100+1
else:
cur_day += 1
days.append(cur_day)
return days
days = all_day(20200122,20200608)
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
def get_colordict():
area_list1 = set(df['provinceShortName'])
color_list = []
for i in range(len(area_list1)):
str_1 = randomcolor()
color_list.append(str_1)
str_1 = randomcolor()
area_list2 = [i for i in area_list1]
color_dict = dict(zip(area_list2,color_list))
return color_dict
draw_barchart(20200607)
animator = animation.FuncAnimation(fig, draw_barchart, frames=days)
#HTML(animator.to_jshtml())
plt.show()