繁体   English   中英

如何在Matplotlib中使用代理艺术家为Contourf图创建图例

[英]How to create legend with proxy artist for contourf plot in Matplotlib

我试图创建一个图形,在其中将多个轮廓图覆盖在单个图像上。 因此,我希望每个图都有颜色条,并有一个说明每个轮廓代表什么的图例。 但是Matplotlib不允许我为轮廓图创建单独的图例。 简单的例子:

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:图例不支持(0x7fa69df7cac8处的matplotlib.contour.QuadContourSet对象)实例。 可以代替使用代理艺术家。 请参阅: 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

因此,您的示例可能类似于:

%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()

在此处输入图片说明

暂无
暂无

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

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