【问题标题】:How can I set a special colour for `Nan`s in my plot?如何在我的情节中为“Nan”设置特殊颜色?
【发布时间】:2020-01-13 05:30:18
【问题描述】:

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

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

我想通过根据关联的数字为每个省份着色来可视化数据。当我这样做时,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')

【问题讨论】:

  • 用某个值替换NaN 值怎么样?喜欢canada.fillna(0.25)
  • 过滤 nan 值:canada = canada.dropna(thresh=1).
  • @ysearka 我希望各省显示为白色。用一个值填充它们会将它们映射为非白色
  • @Serenity 如果我放弃 Nans,省份将不会被绘制

标签: python pandas matplotlib geopandas


【解决方案1】:

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

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

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

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

【讨论】:

    【解决方案2】:

    你可以合并两层:

    ## import statements
    import geopandas as gpd
    import numpy as np
    import matplotlib.pyplot as plt
    
    ## load the Natural Earth data set 
    world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
    
    ## add a column with NaNs
    ## here we set all countries with a population > 10e7 to nan
    world["pop_est_NAN"] = world.pop_est.apply(lambda x: x if x <10e7 else np.nan)
    
    ## first layer, all geometries included 
    ax = world.plot(color="grey")
    
    ## second layer, NaN geometries excluded
    ## we skip the entries with NaNs by calling .dropna() on the dataframe
    ## we reference the first layer by ax=ax
    ## we specify the values we want to plot (column="pop_est")
    world.dropna().plot(ax=ax, column="pop_est")
    
    ## add title
    ax.set_title("Countries with a population > 10e7 (= missing values) \nare plotted in grey");
    
    ## save fig
    plt.savefig("geopandas_nan_plotting.png", dpi=200)
    

    查看geopandas 文档,了解使用matplotlib 对象的替代方法。

    【讨论】:

      猜你喜欢
      • 2016-12-12
      • 2019-09-21
      • 2014-06-20
      • 2015-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多