如何在我的情节中为`Nan`s 设置特殊颜色?

Dem*_*nos 2 python matplotlib pandas geopandas

这是我试图可视化的数据示例

Prince Edward Island    2.333
Manitoba                2.529
Alberta                 2.6444
British Columbia        2.7902
Saskatchewan            2.9205
Ontario                 3.465
New Brunswick           3.63175
Newfoundland and Labrador   3.647
Nova Scotia             4.25333333333
Quebec                  4.82614285714
Nunavut                 NaN
Yukon                   NaN
Northwest Territories   NaN
Run Code Online (Sandbox Code Playgroud)

我想通过根据与每个省相关联的数字为每个省着色来可视化数据。当我这样做时,Nan 的颜色就像颜色图的最小值。有没有一种简单的方法可以将 Nan 映射到白色?

这是我的代码:

plt.figure(figsize=(15,15)) 


vmin, vmax = canada.Partying.min(), canada.Partying.max()

ax = canada.plot(column='Partying', cmap='viridis', vmin=vmin, vmax=vmax)

# add colorbar
fig = ax.get_figure()
cax = fig.add_axes([0.9, 0.1, 0.03, 0.8])
sm = plt.cm.ScalarMappable(cmap='viridis', norm=plt.Normalize(vmin=vmin, vmax=vmax))
# fake up the array of the scalar mappable. Urgh...
sm._A = []
fig.colorbar(sm, cax=cax)
plt.savefig('Canada.pdf')
Run Code Online (Sandbox Code Playgroud)

CPB*_*PBL 5

更新:新功能 geopandas解决了您的问题:您现在可以使用:

ax = canada.plot(column='Partying', cmap='viridis', vmin=vmin, vmax=vmax,
     missing_kwds= dict(color = "lightgrey",) )
Run Code Online (Sandbox Code Playgroud)

使所有缺失的数据区域呈浅灰色。

请参阅https://geopandas.readthedocs.io/en/latest/mapping.html (实际上,文档可能会说参数是missing_kwdsdict,但以上对我有用)