繁体   English   中英

如何在cartopy图中添加图例?

[英]How to add a legend to cartopy plot?

我目前正在处理一些涉及土地利用类型(即森林、沙漠、水等)的数据,这些数据在我的地图上以不同的颜色出现。 我想添加一个图例或等效项来显示每种颜色代表的土地类型,但似乎无法让它发挥作用。 在地图上绘制的土地利用类型数据需要我使用 pcolormesh。 有没有什么办法可以在地图上显示每种土地利用类型的颜色?

以下是我的代码的cartopy部分:

proj = ccrs.LambertConformal(central_longitude=cLon, central_latitude=cLat)
res = '10m'
fig_1 = plt.figure(figsize=(20,20))
ax_1 = plt.subplot(1,1,1,projection=proj)
ax_1.set_extent([lonW,lonE,latS,latN])
ax_1.add_feature(cfeature.LAND.with_scale(res))
ax_1.add_feature(cfeature.OCEAN.with_scale(res))
ax_1.add_feature(cfeature.COASTLINE.with_scale(res))
ax_1.add_feature(cfeature.LAKES.with_scale(res), alpha = 0.5)
ax_1.add_feature(cfeature.STATES.with_scale(res));
ax_1.set_title('Land Use Type: Western United States', fontsize=20)
ax_1.pcolormesh(cat_land_lons, cat_land_lats, cat_land, transform=ccrs.PlateCarree(), zorder=3)
ax_1.legend(['Forested', 'Water', 'Desert', 'Farmland', 'Urban'])

如果不知道您的数据是什么样子,很难具体说明。 但是给出了一些示例土地覆盖数据和分配的颜色。 如果您的 LCC 数据不是这样连续的,情况可能会有所不同。

lc_colors = {
    'Forested': "g", # value=0
    'Water': "b",    # value=1
    'Desert': "y",   # value=2
    'Farmland': "c", # value=3
    'Urban': "r",    # value=4
}

yy, xx = np.mgrid[35:45:1, -120:-110:1]
zz = np.random.randint(0, len(lc_colors), xx.shape)

您可以定义颜色图和规范化器:

cmap = mpl.colors.LinearSegmentedColormap.from_list("lcc", list(lc_colors.values()))

bounds = np.arange(len(lc_colors)+1)
norm = mpl.colors.BoundaryNorm(bounds, cmap.N)

为图例使用代理艺术家

import matplotlib.pyplot as plt
import matplotlib as mpl
import matplotlib.patches as mpatches
import cartopy.crs as ccrs
import cartopy.feature as cfeature
import numpy as np

proj = ccrs.LambertConformal(central_longitude=-110, central_latitude=40)

fig, ax = plt.subplots(figsize=(6,6), facecolor="w", dpi=86, subplot_kw=dict(projection=proj))
ax.set_title('Land Use Type: Western United States', fontsize=15)

im = ax.pcolormesh(xx, yy, zz, transform=ccrs.PlateCarree(), cmap=cmap, norm=norm)
ax.set_extent([-125, -95, 30, 50], crs=ccrs.PlateCarree())

res = '110m'
ax.add_feature(cfeature.LAND.with_scale(res))
ax.add_feature(cfeature.OCEAN.with_scale(res))
ax.add_feature(cfeature.COASTLINE.with_scale(res))
ax.add_feature(cfeature.LAKES.with_scale(res), alpha=0.5)
ax.add_feature(cfeature.STATES.with_scale(res), lw=0.5, alpha=.5)

labels, handles = zip(*[(k, mpatches.Rectangle((0, 0), 1, 1, facecolor=v)) for k,v in lc_colors.items()])
ax.legend(handles, labels, loc=4, framealpha=1)

在此处输入图像描述

或者,不要使用上面代码片段的最后两行,而是使用pcolormesh的结果和颜色条:

cb = fig.colorbar(im, ax=ax, shrink=.3, aspect=8)
cb.set_ticks(bounds[:-1]+0.5)
cb.set_ticklabels(lc_classes.keys())

在此处输入图像描述

从 dataviz 的角度来看,对代理艺术家使用适当的图例可能会更好,因为颜色条可能会建议类的某种顺序。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM