python中plotly绘制树地图_使用Python Plotly库实现COVID-19数据可视化和动态地图制作...

Plotly是一个基于浏览器的开源的Python图形库,具有良好的交互性,提供了许多非常酷炫的图表类型(如条形图,散点图,地图等),其中地图库是基于MapBox来实现。MapBox是现在比较流行的一款开源的地图框架,提供了Windows、Linux和Android等平台下的解决方案,Plotly酷炫的地图显示就是通过调用MapBox相关的一些API来实现。Plotly最吸引的地方是通过简单的代码实现酷炫的动画制作。通过本文学习,你将掌握:使用Plotly绘制条形图使用Plotly绘制线和标记使用Plotly绘制动态地理散布图。

环境安装和数据集准备

首先安装相关库(默认你之前已经安装了Python的相关环境,并安装了pip):

pip install plotly_express==0.4.1

COVID-19的数据集在网上开源的已经很多了,本文采用由Johns Hopkins University Center for Systems Science and Engineering (JHU CCSE)编译的数据集,官网链接: https://data.humdata.org/.

导入Plotly 相关库import plotlyimport plotly.express as pximport plotly.graph_objects as goimport pandas as pdimport numpy as np

数据预处理

从网上下载的数据集因为是不同类型的单个csv数据文件,所以需要对数据进行预处理。

在预处理过程中会使用到Numpy和Pandas的一些知识,本文不详细展开讨论。最后预处理的结果如下:

Plotly绘图原理

Plotly提供2类图形对象,一类是Trace,另一类是Layout。Trace和Layout都有各自的属性,具体可以参考Plotly的官网。我们可以通过使用Figure()函数来调用Plotly中的图形对象。

绘制条形图

我们的数据集中目前有3类数据:confirmed(确诊病例)、deaths(死亡病例)和recovered(治愈病例),我们再增加一种:activated(活跃病例)。为了让4种数据都能在一个图表中显示,可以使用add_trace()函数在1个图层(Layout)中添加4个Trace,每一个Trace中用Bar()函数绘制条形图bar。

fig_barcahrt = go.Figure(go.Bar(x=dates, y=confirmed, name='Total Cofirmed', marker_color='indianred', opacity=.8))fig_barcahrt.add_trace(go.Bar(x=dates, y=confirmed-deaths-recovered, name='Total Active', marker_color='mediumblue', opacity=0.7))fig_barcahrt.add_trace(go.Bar(x=dates, y=recovered, name='Total recovered', marker_color='lightseagreen', opacity=0.8))fig_barcahrt.add_trace(go.Bar(x=dates, y=deaths, name='Total deaths', marker_color='gray', opacity=1))#here we define layout of the chartfig_barcahrt.update_layout(barmode='overlay', xaxis={'categoryorder':'total ascending'},xaxis_type='category', title={ 'text': 'Cummulative COVID-19 world trend', 'y':0.79,'x':0.45, 'xanchor': 'center', 'yanchor': 'top'},)fig_barcahrt.update_xaxes(title= '----->Timeline' ,showline=Truefig_barcahrt.update_yaxes(title= '----->Number of cases', showline=True)fig_barcahrt.show()输出:

绘制线和标记

对数据集中的数据进行求导来更加直观的分析病例数每天的变化情况:df_diff = totalData[['Total_confirmed', 'Total_deaths', 'Total_recovered','Active']].diff()

同样的,为了让4种数据都能在一个图表中显示,使用add_trace()函数在1个图层(Layout)中添加4个Trace,每一个Trace中用Line()函数绘制线。

fig_inc = go.Figure(go.Line(x=df_diff['Dates'], y=df_diff['Total_confirmed'],name='Infected', mode='lines+markers',marker=dict(size=10,color='indianred')))fig_inc.add_trace(go.Line(x=df_diff['Dates'], y=df_diff['Total_recovered'],name='Recovered', mode='lines+markers',marker=dict(size=10,color='lightseagreen')))fig_inc.add_trace(go.Line(x=df_diff['Dates'], y=df_diff['Total_deaths'], name='Deaths', mode='lines+markers',marker=dict(size=10,color='gray')))fig_inc.add_trace(go.Line(x=df_diff['Dates'], y=df_diff['Active'], name='Active', mode='lines+markers',marker=dict(size=10,color='Orange')))#here we define layout of the chartfig_inc.update_layout(xaxis_showgrid=True, yaxis_showgrid=True, plot_bgcolor='whitesmoke', title={'text': 'Incremental COVID-19 world trend', 'y':0.75, 'x':0.5, 'xanchor': 'center', 'yanchor': 'top'},xaxis_type='category')fig_inc.update_xaxes(title= '------>Timeline' ,showline=False)fig_inc.update_yaxes(title= '------>Number of incremental cases', showline=False)输出:

动态地理散布图

Plotly最酷炫的功能就是制作动画,其绘制方式也是非常的简单。Plotly绘制地图是通过调用scatter_mapbox()函数来显示MapBox地图模块的。具体可以参考Plotly官网demo 。绘制COVID-19 地理散布图的数据集还是在前面提到的网站下载,为了让数据显示的更加美观,我增加了一列Norm,即对显示的数据进行了标准化。fig_anim_map = px.scatter_mapbox(df_map, lat='Lat', lon='Long',     color='Infected', size=df_map['Norm']**0.5*50,                color_continuous_scale='Rainbow', size_max=50, animation_frame='Date',                center=dict({'lat': 32, 'lon': 4}), zoom=0.7, hover_data= ['Country']) fig_anim_map.update_layout(mapbox_style='carto-positron',width=900,    height=700)fig_anim_map.update_layout(margin={'r':0,'t':0,'l':0,'b':0})fig_anim_map.layout.updatemenus[0].buttons[0].args[1]['frame']['duration'] = 200fig_anim_map.layout.sliders[0].currentvalue.xanchor='left'fig_anim_map.layout.sliders[0].currentvalue.offset=-100fig_anim_map.layout.sliders[0].currentvalue.prefix=''fig_anim_map.layout.sliders[0].len=.9figanim_map.layout.sliders[0].currentvalue.font.color='indianred'fig_anim_map.layout.sliders[0].currentvalue.font.size=20fig_anim_map.layout.sliders[0].y= 1.1fig_anim_map.layout.sliders[0].x= 0.15fig_anim_map.layout.updatemenus[0].y=1.27fig_anim_map.show()输出:

文章前面的动图就是最后的显示效果。

总结

Plotly绘制各种图表的方式是通过在图层Layout中添加Trace来实现的,而Trace中可以绘制各种Bar、Line等图元。Plotly地图的绘制是通过调用MapBox的地图模块,利用scatter_mapbox()函数来实现。

你可能感兴趣的:(python中plotly绘制树地图_使用Python Plotly库实现COVID-19数据可视化和动态地图制作...)