最近正好在学空间数据处理,这次更一下用python如何画出好看的地图
下面主要是用
folium
poltly
geopandas+matplotlib
import folium
import pandas as pd
#输入上海经纬度,尺度
latitude = 31.2
longitude = 121.5
sh_map = folium.Map(location=[latitude, longitude], zoom_start=10)
sh_map
默认为’OpenStreetMap’风格,我们还可以选择’Stamen Terrain’, 'Stamen Toner’等
sh_map = folium.Map(location=[latitude, longitude], zoom_start=10,tiles='Stamen Toner')
sh_map
有了底图把带有经纬度的数据点映射上去,这里用上次上海poi中的火锅数据
把火锅店数据放到地图上
# 创建特征组
hotpots = folium.map.FeatureGroup()
# Loop through the 200 crimes and add each to the incidents feature group
for lat, lng, in zip(data.lat, data.lon):
hotpots.add_child(
folium.CircleMarker(
[lat, lng],
radius=7, # define how big you want the circle markers to be
color='yellow',
fill=True,
fill_color='red',
fill_opacity=0.4
)
)
# 把火锅特征组放到上海地图上
sh_map =folium.Map(location=[latitude, longitude], zoom_start=10)
sh_map.add_child(hotpots)
点太多看不出什么,我们下面只放嘉定区的数据
我们可以继续添加火锅店名字信息并标注在上图
latitudes = list(datas.lat)
longitudes = list(datas.lon)
labels = list(datas.name)
for lat, lng, label in zip(latitudes, longitudes, labels):
folium.Marker([lat, lng], popup=label).add_to(sh_map)
sh_map
最后我们需要绘制每个区的火锅数量的Choropleth Map,不同颜色代表火锅数量
首先读取上海行政区geojson文件
统计各个区火锅数量
hots=data.groupby('adname',as_index=False).agg({'name':"count"})
hots.columns=['district','num']
hots
开始绘制Choropleth Map, 下面key_on='feature.properties.name’是因为我们这里下载的上海geojson中name对应于行政区,这个根据具体数据而定
#输入上海经纬度,尺度
latitude = 31.2
longitude = 121.5
map = folium.Map(location=[latitude, longitude], zoom_start=12)
folium.Choropleth(
geo_data=geo_data,
data=hots,
columns=['district','num'],
key_on='feature.properties.name',
#fill_color='red',
fill_color='YlOrRd',
fill_opacity=0.7,
line_opacity=0.2,
highlight=True,
legend_name='Hotpot Counts in Shanghai'
).add_to(map)
map
用poltly画Choropleth Map跟folium很类似,这里直接继续用前面处理好的数据
import plotly.express as px
import plotly.graph_objs as go
latitude = 31.2
longitude = 121.5
fig = px.choropleth_mapbox(
data_frame=hots,
geojson=geo_data,
color='num',
locations="district",
featureidkey="properties.name",
mapbox_style="carto-positron",
color_continuous_scale='viridis',
center={"lat": latitude, "lon": longitude},
zoom=7.5,
)
fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0})
fig.show()
设置mapbox_style="carto-darkmatter"换一种风格
先利用geopandas绘制出各行政区轮廓
import matplotlib.pyplot as plt
import matplotlib as mpl
# 中文和负号的正常显示
mpl.rcParams['font.sans-serif'] = ['Times New Roman']
mpl.rcParams['font.sans-serif'] = [u'SimHei']
mpl.rcParams['axes.unicode_minus'] = False
# 裁剪上海shape
fig, ax = plt.subplots(figsize=(20, 10))
ax=geo_data.plot(ax=ax,facecolor='grey',edgecolor='white',linestyle='--',alpha=0.8)
ax.axis('off') # 移除坐标轴
need_data=pd.merge(geo_data,hots[['district','num']],left_on='name',
right_on='district')
need_data
此时数据已经是dataframe,不是需要的geodataframe了,所以需要继续转换一下
need_data = gpd.GeoDataFrame(need_data)
need_data.geom_type
可以看到这个时候need_data已经是geodataframe类型了
fig, ax = plt.subplots(figsize=(20, 10))
need_data.plot('num', cmap='OrRd',ax=ax)
ax.axis('off') # 移除坐标轴
cmap = mpl.cm.get_cmap('OrRd')
norm = mpl.colors.Normalize(min(need_data['num']), max(need_data['num']))
fcb = fig.colorbar(mpl.cm.ScalarMappable(norm=norm, cmap=cmap),ax=ax)
ax=geo_data.plot(ax=ax,facecolor='grey',edgecolor='white',linestyle='--',alpha=0.2)
ax.set_title('Hotpot Count in Shanghai', fontsize=20)
fig, ax = plt.subplots(figsize=(20, 10))
need_data.plot('num', cmap='OrRd',ax=ax)
for idx, _ in enumerate(need_data.geometry.representative_point()):
# 提取行政区名称
region = need_data.loc[idx, 'name']
ax.text(_.x, _.y, region, ha="center", va="center", size=8)
ax.axis('off') # 移除坐标轴
cmap = mpl.cm.get_cmap('OrRd')
norm = mpl.colors.Normalize(min(need_data['num']), max(need_data['num']))
fcb = fig.colorbar(mpl.cm.ScalarMappable(norm=norm, cmap=cmap),ax=ax)
ax=geo_data.plot(ax=ax,facecolor='grey',edgecolor='white',linestyle='--',alpha=0.2)
ax.set_title('Hotpot Count in Shanghai', fontsize=20)
本文的notebook及数据可公众号后台回复地图获得