如何在matplotlib中创建自定义阴影范围?

3

问题

我有两个100x100的数组-一个是数据(我将其称为array1),另一个是一些较小的比例数据(我将其称为array2)。我创建了一个测试数组,以查看array2+array1在某些阈值上方或下方,每个点的结果应该是三种结果之一-对于该点,array1+array2是>5、>10还是<5。根据结果,我创建了一个新的100x100数组(array3),并分别给该点赋值1.、2.或0。

现在我想使用plt.contourf()绘制array1和array3,并且我希望后者的子图具有填充。我希望填充范围为x=0、x=1和x=2。查看文档,我知道我可能不能这样做,所以我会说x<1,1<=x,<2和x=>2。唯一的问题是我不知道如何指定这些范围。

代码(可工作示例)

这是问题的完整代码。

#Make data array1
array1 = np.empty([10,10])
for i in range(10):
    for j in range(10):
        array1[i,j] = i+j
print array1

#Make data array2
array2 = np.empty([10,10])
for i in range(10):
    for j in range(10):
        array2[i,j] = (i*0.25)+(j*0.25)
print array2

#Make range test array3
array3 = np.empty([10,10])
for i in range(10):
    for j in range(10):
        if array1[i,j]+array2[i,j] > 5 and array1[i,j]+array2[i,j] > 10:
            array3[i,j] = 2
        elif array1[i,j]+array2[i,j] > 5:
            array3[i,j] = 1
        else:
            array3[i,j] = 0
print array3

#Plot
from matplotlib.patches import Ellipse, Polygon
xgrid = np.arange(0,10)
ygrid = np.arange(0,10)
n_levels=2
plt.contourf(xgrid, ygrid, array1)
stip = plt.contourf(xgrid, ygrid, array3, n_levels, colors='none',
              hatches=[None,'.', '/'],
              extend='lower')
#create a legend for the contour set
artists, labels = stip.legend_elements()
plt.legend(artists, labels, handleheight=2)
plt.show

enter image description here

请注意图例。我希望范围是x<1,1<=x<2和x>=2,而不是包中自动分配的范围。

问题

如何为我的阴影图案指定自定义范围?我计划让这个例子起作用,以便我可以将它翻译成一个Basemap图,其中有lat-lon数据,并在此基础上有一个点彩阵列,该阵列与两个其他阵列的数据+S.D.进行比较。我希望根据每个网格点的情况,如果该lat-lon数据大于一个data+S.D.数组、另一个data+S.D.数组或两个数组,则使用不同的点彩阵列。

1个回答

3

如果您需要更多控制轮廓线的级别,请使用levels关键字。

stip = plt.contourf(xgrid, ygrid, array3, levels=[-1, 0, 1, 2],
                    colors='none', hatches=[None,'.', '/'])
artists, labels = stip.legend_elements()
plt.legend(artists, labels, handleheight=2)

enter image description here


谢谢,你知道我怎么可以制作自定义图例标签吗?stip.legend_elements()这一行把我难住了。 - Cebbie
@ChristineB 标签只是字符串或任何可以转换为字符串的对象,请参阅 legend()图例指南 上的文档。 - Stop harming Monica

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接