由于对空间数据可视化的喜欢,可能本公众号的推文也以此类图较多,当然也受到小伙伴的喜欢。在R语言ggplot2以及其拓展包能够较为简单的实现各类空间可视化作品的绘制,在寻找Python进行空间绘制包的同时,也发现如geopandas、geoplot等优秀包,今天的推文就简单使用geoplot库绘制空间核密度估计图,涉及的知识点如下:
所使用的数据为全国PM2.5站点数据和中国地图文件。
geoplot库就相当于seaborn 对matplotlib一样,实现了较多绘图函数的封装,使你可以使用较少的代码绘制较精美的图表,更多详细内容,大家可以直接去官网进行查看:Geoplot官网我们只介绍本推文需要的绘图函数,首先,我们绘制空间散点图, 数据预览如下:
再使用geopandas包对相关处理,具体代码如下:
scattergdf = gpd.GeoDataFrame(
scatter, geometry=gpd.points_from_xy(scatter.经度, scatter.纬度),
crs="EPSG:4326")
这样就可以把数处理成geoplot 绘图所需的数据格式了,绘图代码具体如下:
plt.rcParams['font.family'] = ["Times New Roman"]
fig,ax = plt.subplots(figsize=(8,5),dpi=200)
proj = projection=gcrs.AlbersEqualArea(central_latitude=40, central_longitude=104)
ax = plt.subplot(projection=proj,frameon=False)
gplt.pointplot(
scattergdf, projection=proj,
s=4,
hue="PM2.5",
cmap='Spectral_r',
edgecolor='black', linewidth=0.2,
legend=True,
ax=ax,
)
gplt.polyplot(china_main, linewidth=.3,ax=ax)
gplt.polyplot(china_nine, linewidth=.3,ax=ax)
plt.title("Geoplot Test",fontsize = 20)
plt.text(.88,.02,'\nVisualization by DataCharm',transform = ax.transAxes,
ha='center', va='center',fontsize = 5,fontweight="bold")
代码较为简单,我们直接给出可视化结果,如下:
由于geoplot的高度封装,我们直接使用kdeplot()函数进行绘制,具体代码如下:
fig,ax = plt.subplots(figsize=(8,5),dpi=200)
proj = projection=gcrs.AlbersEqualArea(central_latitude=40, central_longitude=104)
ax = plt.subplot(projection=proj)
gplt.kdeplot(
scattergdf,
cmap = "Spectral_r",
clip = china_main.geometry,
projection=proj,
levels=12,
thresh=.0005,
shade=True,
ax=ax,
)
gplt.polyplot(china_main, zorder=1,facecolor="none",linewidth=.3,ax=ax)
plt.title("Geoplot Test2",fontsize = 18)
plt.text(.85,.25,'\nVisualization by DataCharm',transform = ax.transAxes,
ha='center', va='center',fontsize = 5,fontweight="bold")
就完成了空间核密度估计的可视化绘制,所涉及的绘图函数相对简单,大家看看官网教程就可以快速掌握。
Python-geoplot库对一些空间图表可以较为迅速的绘制出结果,可以说是相对简单,但到实践过程中,也发现一些问题(完全自己绘制过程中的感悟啊,可能存在个人原因啊):