How to create legend with proxy artist for contourf plot in Matplotlib
我试图创建一个图形,在其中将多个轮廓图覆盖在单个图像上。 因此,我希望每个图都有颜色条,并有一个说明每个轮廓代表什么的图例。 但是Matplotlib不允许我为轮廓图创建单独的图例。 简单的例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | import matplotlib as mpl import matplotlib.pyplot as plt import cartopy import cartopy.crs as ccrs import numpy as np def create_contour(i,j): colors = ["red","green","blue"] hatches = ['-','+','x','//','*'] fig = plt.figure() ax = plt.axes(projection=ccrs.PlateCarree()) ax.set_extent((-15.0,15.0,-15.0,15.0)) delta = 0.25 x = np.arange(-3.0,3.0,delta) y = np.arange(-2.0,2.0,delta) X, Y = np.meshgrid(x, y) data = np.full(np.shape(X), 1.0) plot = ax.contourf(X,Y,data, levels = [float(i),float(i+1)], hatch=[hatches[j]], colors = colors[i], label="label") plt.legend(handles=[plot], labels=["label"]) plt.savefig("figure_"+str(i)+".png") create_contour(1,3) |
运行此命令时,收到以下消息:
UserWarning: Legend does not support
(matplotlib.contour.QuadContourSet object at 0x7fa69df7cac8)
instances. A proxy artist may be used instead. See:
http://matplotlib.org/users/legend_guide.html#creating-artists-specifically-for-adding-to-the-legend-aka-proxy-artists
"aka-proxy-artists".format(orig_handle)
但是据我所知,我会尽可能地遵循这些指示,唯一的区别是在示例中它们不使用contourf。
任何帮助将不胜感激。
您对问题的评论似乎已经解决了问题(通过制作自定义补丁并将其传递给图例)。 还有一个例子,我很多年前在matplotlib文档中添加了一个类似的东西(大约在我向matplotlib添加轮廓阴影的同时):https://matplotlib.org/examples/pylab_examples/contourf_hatching.html#pylab- examples-contourf阴影
这是一个合理的要求,轮廓集上甚至还提供了一种方法来为您提供开箱即用的图例代理:ContourSet.legend_elements。
因此,您的示例可能类似于:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | %matplotlib inline import matplotlib.pyplot as plt import cartopy.crs as ccrs import numpy as np fig = plt.figure(figsize=(10, 10)) ax = plt.axes(projection=ccrs.PlateCarree()) ax.coastlines('10m') y = np.linspace(40.0, 60.0, 30) x = np.linspace(-10.0, 10.0, 40) X, Y = np.meshgrid(x, y) data = 2*np.cos(2*X**2/Y) - np.sin(Y**X) cs = ax.contourf(X, Y, data, 3, hatches=['//','+','x','o'], alpha=0.5) artists, labels = cs.legend_elements() plt.legend(handles=artists, labels=labels) plt.show() |