1.首先读入原始数据
main_country.csv文件地址:
链接:https://pan.baidu.com/s/1Joa4i4mM2vHgRVS9p8I2SQ
提取码:e3tc
2.对每一年的GDP数据进行排名
需要说明的是,这里先对GGP数据进行逆序排序,然后用11减去排名,这样可以保证GDP最高的国家排名最大,而且可是使GDP最大的10个国家的排名为正,在最终的展示结果中,我们只展示GDP排名前10的国家。
3. 具体画图
先上代码,具体如下:
import matplotlib.pyplot as plt
import matplotlib
import matplotlib.animation as animation
import imageio
%matplotlib auto
matplotlib.rc('font', family='SimHei', weight='bold')
plt.rcParams['axes.unicode_minus'] = False
fig,ax=plt.subplots()
#去掉右侧和上边的边框线
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.spines['left'].set_color('none')
colors=['cornflowerblue','tomato','coral','darksalmon','orangered','sienna','chocolate',
'saddlebrown','orange','burlywood','olive','olivedrab','greenyellow','lawngreen',
'orchid','palegreen','aqua','deepskyblue','dodgerblue','darkviolet','crimson']
image_list=[]
for i in range(286):
ax.cla()
ax.set_ylim(0,11)
y_ind=str(1960+i//5)
if i==285:
data=gdp_rank_data[['Country_Name',y_ind,y_ind+'_rank']]
data['step_rank']=data[y_ind+'_rank']
x_gdp=data[y_ind]
else:
next_y_ind=str(1960+i//5+1)
data=gdp_rank_data[['Country_Name',y_ind,y_ind+'_rank',next_y_ind,
next_y_ind+'_rank']]
data['step_rank']=data[y_ind+'_rank']+(data[next_y_ind+'_rank']
-data[y_ind+"_rank"])/5*(i%5)
x_gdp=data[y_ind]+(data[next_y_ind]-data[y_ind])/5*(i%5)
y_labels=data.index
bars=ax.barh(data['step_rank'],x_gdp,color=[colors[i] for i in data.index],height=0.5)
data=data.sort_values('step_rank',na_position='first')
ax.set_yticks(data[data['step_rank']>=0]['step_rank'].values[-10:])
ax.set_yticklabels(data[data['step_rank']>=0]['Country_Name'].values[-10:])
ax.set_title("世界GDP动态排名(1960年-2017年)(单位:十亿)")
for bar in bars:
if bar.get_y()>0:
width=bar.get_width()
plt.text(width+ax.get_xlim()[1]*0.02,bar.get_y()+0.125,"{:.2f}".format(width))
#在柱子的四个角上加上四个点
plt.plot([0,width,width,0],
[bar.get_y(),bar.get_y(),bar.get_y()+0.5,bar.get_y()+0.5],color=bar.get_facecolor(),
marker='o')
plt.text(int(ax.get_xlim()[1]*0.8),2,y_ind+'年',fontsize=18)
if i%5==0:
plt.pause(3)
else:
plt.pause(0.3)
plt.savefig('tmp.png')
image_list.append(imageio.imread('tmp.png'))
imageio.mimsave('test.gif',image_list,duration=1)
最终结果如下:
我的代码是在jupyter中运行的,在jupyter中显示出动态图,需要加上%matplotlib auto,否则无法动态显示。