本期,利用Python/Plotly工具制作自2000年以来中国各省份(不含港澳台地区)人口数量变化,数据来源:国家统计局
具体代码为:
import pandas as pd import plotly.graph_objects as go#导入相关的csv文件df=pd.read_csv('population.csv',encoding='gbk')df['colors']=['aliceblue','antiquewhite','aqua','aquamarine','azure','beige','bisque','black','blanchedalmond','blue','blueviolet','brown','burlywood','cadetblue','chartreuse','chocolate','coral','cornflowerblue','red','crimson','cyan','darkblue','darkcyan','darkgoldenrod','darkgray','darkgreen','darkkhaki','darkmagenta','darkolivegreen','darkorange','darkorchid'] ani_frames=[] for i in df.columns[1:-1][::-1]: df.sort_values(by=i,inplace=True) bar=go.Bar(x=df[i],y=df['地区'],orientation='h',textposition='outside',marker_color=df['colors'],text=df[i]) frame=go.Frame(data=bar,layout=go.Layout(title=i+'各省份常驻人口数量(万人)',title_x=0.5)) ani_frames.append(frame) d_inf=df.loc[:,['2000年','地区','colors']]d_inf.sort_values(by='2000年',inplace=True) ini_bar= go.Bar(x=d_inf['2000年'],y=d_inf['地区'],orientation='h',textposition='outside',marker_color=d_inf['colors'],text=d_inf['2000年']) buttons={ "type":"buttons", "direction":"right", "pad":{"r":80,"t":0}, "buttons":[{"label":"Play","method":"animate","args":[ None, dict(frame=dict(duration=600,redraw=True), transition=dict(duration=1800,easing="linear-in-out"), fromcurrent=True, mode='immediate') ]}]} fig=go.Figure( data=[ini_bar], layout=go.Layout( title="2000年各省份常驻人口数量(万人)", title_x=0.5, width=1000,height=750, updatemenus=[buttons], xaxis=dict(showgrid=True,zeroline=False,automargin=True,range=[0,12500]), yaxis=dict(showgrid=True,zeroline=False,automargin=True) ), frames=ani_frames )fig.update_yaxes(nticks=40)fig.show()
看个运行效果的小动画:
源文件:population.csv我放到了以下地址: