gpt4 book ai didi

plot - 使用 Geopandas 绘制缺失值

转载 作者:行者123 更新时间:2023-12-03 21:18:12 24 4
gpt4 key购买 nike

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

这不是我想要的。
因此,我用字符串“missing”替换缺失值,然后重做绘图。不出所料,我收到错误消息 TypeError: '<' not supported between instances of 'str' and 'float' .

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

最佳答案

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)
enter image description here
您可能需要查看以下帖子:
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 plot函数中的arg:
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)

关于plot - 使用 Geopandas 绘制缺失值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58014486/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com