如何为我的图中的`Nan`设置特定颜色?

2024-10-01 04:53:40 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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的颜色就像colormap的最小值一样。有没有一种简单的方法可以将Nan映射为白色?在

这是我的代码:

^{pr2}$

Tags: 数据示例new可视化nanedwardprinceisland
1条回答
网友
1楼 · 发布于 2024-10-01 04:53:40

您可以合并两层:

## 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_nan_plotting

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

相关问题 更多 >