python - 如何使用 geopandas 和 mapclassify 绘制“差异”地图?
问题描述
我有GeoDataFrame
一个“差异”列,用于存储两个数字之间的增量。有时,如果没有差异,这些数字是正数、负数或零。我需要制作一个 choropleth 地图,它有一些不同的颜色图,其中 0(或一些中间缓冲区)作为中点和非对称颜色条,例如 [ -0.02, -0.01, 0., 0.01, 0.02, 0.03
]。我已经尝试过
class MidPointNormalize(mp.colors.Normalize):
def __init__(self, vmin=None, vmax=None, midpoint=None, clip=False):
self.midpoint = midpoint
mp.colors.Normalize.__init__(self, vmin, vmax, clip)
def __call__(self, value, clip=None):
x, y = [self.vmin, self.midpoint, self.vmax], [0, 0.5, 1]
return np.ma.masked_array(np.interp(value, x, y), np.isnan(value))
norm = MidPointNormalize(midpoint=0,vmin=diff_merge_co["diff"].min(),
vmax=diff_merge_co["diff"].max())
diff_merge_co.plot(ax=ax, column="diff", cmap="coolwarm", norm=norm,
legend=True)
并设置norm
为一些精心挑选的值:
bounds = np.array([-0.02, -0.01, 0., 0.01, 0.02, 0.03])
norm = colors.BoundaryNorm(boundaries=bounds, ncolors=256)
但是有很多技术问题(包括颜色条没有向上持续,以及手工挑选值的明显丑陋)。
所以我的问题是:你将如何使用不同的比例绘制地图,你会使用geopandas.GeoDataFrame.plot()
哪种mapclassify
方法?
解决方案
我可能不明白这个问题,但两种想法都应该可以正常工作。例如:
import geopandas as gpd
print(gpd.__version__) ## 0.4.1
import numpy as np; np.random.seed(42)
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
class MidPointNormalize(mcolors.Normalize):
def __init__(self, vmin=None, vmax=None, midpoint=None, clip=False):
self.midpoint = midpoint
mcolors.Normalize.__init__(self, vmin, vmax, clip)
def __call__(self, value, clip=None):
x, y = [self.vmin, self.midpoint, self.vmax], [0, 0.5, 1]
return np.ma.masked_array(np.interp(value, x, y), np.isnan(value))
## Some data file from ## http://biogeo.ucdavis.edu/data/diva/adm/USA_adm.zip
gdf = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
quant = np.random.rand(len(gdf))*0.05-0.02
gdf['quant']=quant
print(gdf.head())
fig, (ax, ax2) = plt.subplots(2, figsize=(7,6))
norm=MidPointNormalize(-0.02, 0.03, 0)
gdf.plot(column='quant', cmap='RdBu', norm=norm, ax=ax)
fig.colorbar(ax.collections[0], ax=ax)
bounds = np.array([-0.02, -0.01, 0., 0.01, 0.02, 0.03])
norm2 = mcolors.BoundaryNorm(boundaries=bounds, ncolors=256)
gdf.plot(column='quant', cmap='RdBu', norm=norm2, ax=ax2)
fig.colorbar(ax2.collections[0], ax=ax2)
plt.show()
推荐阅读
- node.js - 从 Typescript 代码生成 Openapi/Swagger
- java - AppCompatActivity 改变了我的 AlertDialog 设计
- selenium - 无头 safari 通过 windows 浏览
- bash - 打印第一列不在列表中的行
- makefile - 如何检测是否设置了 makefile `--silent/--quiet` 命令行选项?
- python - 为什么 Tkinter Scrolledtext 小部件在我的情况下会忽略空格?
- xslt - Datapower_Remove 除 SOAP 到 JSONX XSLT 中的一个以外的所有 Null 元素
- node.js - 无法从异步函数中提取结果,即使它已显示
- php - 如何使用 php 读取一些文件部分
- python - 如何将我的 Tkinter 条目的数据存储到 DataFrame 中,以便以后将其导出到 Excel?