[英]How can I set a special colour for `Nan`s in my plot?
Here is a sample of the data I am trying to visualize这是我试图可视化的数据示例
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
I want to visualize the data by colouring each province according to the number it is associated with.我想通过根据与每个省相关联的数字为每个省着色来可视化数据。 When I do this, the Nan's are coloured like the minimum value of the colormap.
当我这样做时,Nan 的颜色就像颜色图的最小值。 Is there an easy way to map Nan to white?
有没有一种简单的方法可以将 Nan 映射到白色?
Here is my code:这是我的代码:
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')
Update: New feature in geopandas
solves your problem: You can now use:更新:
geopandas
新功能解决了您的问题:您现在可以使用:
ax = canada.plot(column='Partying', cmap='viridis', vmin=vmin, vmax=vmax,
missing_kwds= dict(color = "lightgrey",) )
To make all missing data regions light grey.使所有缺失的数据区域呈浅灰色。
See https://geopandas.readthedocs.io/en/latest/mapping.html (actually, the documentation may say that the parameter is missing_kwdsdict
, but the above is what works for me)请参阅https://geopandas.readthedocs.io/en/latest/mapping.html (实际上,文档可能会说参数是
missing_kwdsdict
,但以上对我missing_kwdsdict
)
You may combine two layers:您可以组合两层:
## 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)
Take a look at the geopandas documentation for an alternative method using matplotlib
objects.查看geopandas文档,了解使用
matplotlib
对象的替代方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.