【问题标题】:use Geopandas plot missing values使用 Geopandas 绘制缺失值
【发布时间】:2020-01-20 16:38:06
【问题描述】:

我的 shapefile 在某些列(例如 GDP)上有一些缺失值(由 nan 表示)。在不处理这些缺失值的情况下进行绘图时,图例显示如下: enter image description here

这不是我想要的。 所以,我用字符串“missing”替换缺失值,然后重做绘图。毫不奇怪,我收到了错误消息,上面写着TypeError: '<' not supported between instances of 'str' and 'float'

我的问题是:1. Geopandas 如何处理缺失值?它是否将缺失值存储在字符串或其他一些类型的数据中? 2. 我怎样才能保留那些缺失的值并用图例标签重做绘图以显示缺失?

【问题讨论】:

标签: plot nan geopandas


【解决方案1】:
import numpy as np
import matplotlib.pyplot as plt
import geopandas as gpd
import pysal.viz.mapclassify as mc
from matplotlib.colors import rgb2hex
from matplotlib.colors import ListedColormap
plt.style.use('seaborn')

gdf = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
# generate random data
gdf['random'] = np.random.normal(100, 10, len(gdf))
# assign missing values
gdf.loc[np.random.choice(gdf.index, 40), 'random'] = np.nan

这里的基本思想是根据您要用于数字数据的分类方法(例如,分位数、百分位数等)创建一个类别/字符串列。之后,我们绘制该字符串列,以便我们可以传递自定义颜色图(用灰色表示缺失值)。

# categorize the numerical column
k = 5
quantiles = mc.Quantiles(gdf.random.dropna(), k=k)
gdf['random_cat'] = quantiles.find_bin(gdf.random).astype('str')

gdf.loc[gdf.random.isnull(), 'random_cat'] = 'No Data'

# add grey to a colormap to represent missing value
cmap = plt.cm.get_cmap('Blues', k)
cmap_list = [rgb2hex(cmap(i)) for i in range(cmap.N)]
cmap_list.append('grey')
cmap_with_grey = ListedColormap(cmap_list)

# plot map
fig, ax = plt.subplots(figsize=(12, 10))
gdf.plot(column='random_cat', edgecolor='k', cmap=cmap_with_grey,
         legend=True, legend_kwds=dict(loc='center left'),
         ax=ax)

# get all upper bounds in the quantiles category
upper_bounds = quantiles.bins
# get and format all bounds
bounds = []
for index, upper_bound in enumerate(upper_bounds):
    if index == 0:
        lower_bound = gdf.random.min()
    else:
        lower_bound = upper_bounds[index-1]

    bound = f'{lower_bound:.2f} - {upper_bound:.2f}'
    bounds.append(bound)

# get all the legend labels
legend_labels = ax.get_legend().get_texts()
# replace the numerical legend labels
for bound, legend_label in zip(bounds, legend_labels):
    legend_label.set_text(bound)

您可能想看看以下帖子:

format/round numerical legend label in GeoPandas

Extract matplotlib colormap in hex-format

Matplotlib.colors.ListedColormap in python

Change main plot legend label text


更新至 geopandas 0.8.1

您现在可以在绘图函数中简单地传递 missing_kwds 参数:

fig, ax = plt.subplots(figsize=(12, 10))

missing_kwds = dict(color='grey', label='No Data')

gdf.plot(column='random', scheme='Quantiles', k= 5,
         legend=True, legend_kwds=dict(loc='center left'),
         missing_kwds=missing_kwds, ax=ax)

【讨论】:

  • 如果可以的话,我会给这个答案一颗星!非常感谢,工作完美无缺,我学到了很多。
【解决方案2】:

更新:geopandas 中的新功能解决了您的问题:您可以将缺失值保留为 NaN 并使用:

ax = gdf.plot( <other arguments>, 
       missing_kwds = dict(color = "lightgrey",) )

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

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

【讨论】:

  • 2022 年 2 月,唯一对我有用的是上面的文档链接。但与这里的其他答案不同。试试world.plot(column='pop_est', missing_kwds={'color': 'lightgrey'});
【解决方案3】:

GeoPandas 目前不支持绘制缺失值。这是计划在 0.7 版本中发布的。可能的解决方案是只绘制那些没有缺失值的行,然后只绘制缺失值。由于您没有给我们任何代码,下面是来自https://nbviewer.jupyter.org/gist/jorisvandenbossche/bb1cc71f94aa3e8f2832f18dd12f6174的示例

import geopandas

gdf = geopandas.read_file(geopandas.datasets.get_path('naturalearth_lowres'))

# Introduce some missing values:
gdf.loc[np.random.choice(gdf.index, 20), 'pop_est'] = np.nan

ax = gdf[gdf.pop_est.notna()].plot(column='pop_est', figsize=(15, 10), legend=True)
gdf[gdf.pop_est.isna()].plot(color='lightgrey', hatch='///', ax=ax)

【讨论】:

  • 这行得通。还有一个问题,即传说中的缺失如何表现?我还查看了这个脚本link,但它也没有显示传说中的缺失。如果缺少小区域,则在地图上可能不明显。但如果有大面积缺失,最好在图例上显示缺失。你能给出一个解决方法吗?谢谢。
  • 这有 github 问题吗?你能把链接贴在这里吗@martinfleis
猜你喜欢
  • 2014-06-09
  • 1970-01-01
  • 2018-01-11
  • 2021-02-23
  • 2021-08-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多