1
六边形地图是一种特定类型的地图,其中每个区域都表示为六边形,使地图更具几何特性,更容易体现更多信息。
import geopandas as gpd
import matplotlib.pyplot as plt
import pandas as pd
plt.rcParams["figure.figsize"]=13,13
# 加载数据
url = "https://raw.githubusercontent.com/holtzy/The-Python-Graph-Gallery/master/static/data/us_states_hexgrid.geojson.json"
geoData = gpd.read_file(url)
geoData.head()
2
import pandas as pd
import seaborn as sns
# 读取美国失业率数据,用来作为区域的数值变量
data = pd.read_csv('https://raw.githubusercontent.com/holtzy/The-Python-Graph-Gallery/master/static/data/unemployment-x.csv')
# 匹配数据
geoData['id'] = geoData['id'].astype('int64')
fullData = geoData.merge(data, left_on=['id'], right_on=['id'])
fullData.head()
3
# 绘制基本的六边形地图框架
geoData.plot(color="white", edgecolor='black', linewidth=.5);
plt.axis('off');
3
# 添加区域名称
# 添加一个“质心”列,其中包含每个区域质心位置
geoData['centroid'] = geoData['geometry'].apply(lambda x: x.centroid)
# 重新绘制
geoData.plot(color="white", edgecolor='black', linewidth=.5);
plt.axis('off');
# 对于每个区域,用位于质心坐标处的区域名称进行注释
for idx, row in geoData.iterrows():
plt.annotate(row['iso3166_2'], xy=row['centroid'].coords[0], horizontalalignment='center', va='center')
4
# 加载结婚率数据
mariageData = pd.read_csv("https://raw.githubusercontent.com/holtzy/The-Python-Graph-Gallery/master/static/data/State_mariage_rate.csv")
# 生成state用于匹配
geoData['state'] = geoData['google_name'].str.replace('(United States)','').str.strip()
# 匹配数据
geoData = geoData.set_index('state').join(mariageData.set_index('state'))
# 绘制分区域统计地图
geoData.plot(column="y_2015", cmap="viridis");
5
# 颜色修饰并增加注释信息
# 初始布局
fig, ax = plt.subplots(1, figsize=(13, 13))
# 依据颜色绘制各个区域的地图
geoData.plot(
ax=ax,
column="y_2015",
cmap="BuPu",
norm=plt.Normalize(vmin=2, vmax=13), # 设置颜色归一化范围
edgecolor='black', # 边界颜色为黑色
linewidth=.5 # 边界线宽度为0.5
);
# 移除无用的坐标轴
ax.axis('off');
# 添加标题、副标题、著作信息
ax.annotate('Mariage rate in the US', xy=(10,620), xycoords='axes pixels', horizontalalignment='left', verticalalignment='top', fontsize=14, color='black')
ax.annotate('Yes, people love to get married in Vegas', xy=(10,590), xycoords='axes pixels', horizontalalignment='left', verticalalignment='top', fontsize=11, color='#808080')
ax.annotate('python-graph-gallery.com', xy=(810,0), xycoords='axes pixels', horizontalalignment='left', verticalalignment='top', fontsize=8, color='#808080')
# 对每一个区域使用其名称注释位于质心坐标的位置
for idx, row in geoData.iterrows():
ax.annotate(
row['iso3166_2'],
xy=row['centroid'].coords[0], # 使用质心坐标作为注释位置
horizontalalignment='center',
va='center',
color="white"
)
# 添加颜色条形图
sm = plt.cm.ScalarMappable(cmap='BuPu', norm=plt.Normalize(vmin=2, vmax=13)) # 创建一个颜色映射器
sm.set_array([]) # 将 ScalarMappable 添加到当前的 Axes 中
fig.colorbar(sm, ax=ax, orientation="horizontal", aspect=50, fraction=0.005, pad=0 ); # 添加颜色条形图