地图(三)利用python绘制等值区域地图
地图(三)利用python绘制等值区域地图
等值区域地图(Choropleth Map)简介
等值区域地图通过颜色区别地图上不同区域的变量,便于在空间上进行变量的比较。
快速绘制
-
基于geopandas和geoplot
import geopandas as gpd import geoplot as gplt # 导入数据 geoData = gpd.read_file('https://raw.githubusercontent.com/holtzy/The-Python-Graph-Gallery/master/static/data/US-counties.geojson') # 删除Alaska、Hawaii、Puerto Rico. stateToRemove = ['02', '15', '72'] geoData = geoData[~geoData.STATE.isin(stateToRemove)] geoData = geoData.explode(index_parts=True) # 外部轮廓 gplt.polyplot(geoData, figsize=(20, 4));
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()
import matplotlib.pyplot as plt fig, ax = plt.subplots(1, 1, figsize=(16, 12)) # 设置颜色方案 import mapclassify as mc scheme = mc.Quantiles(fullData['rate'], k=10) # 绘制choropleth gplt.choropleth(fullData, hue="rate", linewidth=.1, scheme=scheme, cmap='inferno_r', legend=True, edgecolor='black', ax=ax ); ax.set_title('Unemployment rate in US counties', fontsize=13);
-
基于plotly
import pandas as pd import matplotlib.pyplot as plt from urllib.request import urlopen import json import plotly.express as px # 导入数据 df = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/fips-unemp-16.csv", dtype={"fips": str}) # 加载county的边界坐标 with urlopen('https://raw.githubusercontent.com/plotly/datasets/master/geojson-counties-fips.json') as response: counties = json.load(response) # 绘制choropleth fig = px.choropleth(df, geojson=counties, locations='fips', color='unemp', color_continuous_scale="Viridis", range_color=(0, 12), scope="usa", labels={'unemp':'unemployment rate'} ) fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0}) # 修改图例 fig.update_layout(coloraxis_colorbar=dict( thicknessmode="pixels", thickness=10, lenmode="pixels", len=150, yanchor="top", y=0.8, ticks="outside", ticksuffix=" %", dtick=5 )) fig.show()
总结
以上利用geoplot和plotly快速绘制等值区域地图。
共勉~