首页 > 解决方案 > 如果仅使用两个级别,则 Matplotlib 轮廓孵化不起作用

问题描述

我正在尝试在符合此处找到的示例的某些标准的等高线上绘制阴影。然而,我得到了规则的轮廓(黄线)而不是阴影。任何想法如何解决这个问题。谢谢 在此处输入图像描述

import matplotlib.pyplot as plt
import numpy as np
# invent some numbers, turning the x and y arrays into simple
# 2d arrays, which make combining them together easier.
x = np.linspace(-3, 5, 150).reshape(1, -1)
y = np.linspace(-3, 5, 120).reshape(-1, 1)
z = np.cos(x) + np.sin(y)

# we no longer need x and y to be 2 dimensional, so flatten them.
x, y = x.flatten(), y.flatten()
fig2, ax2 = plt.subplots()
n_levels = 6
a=ax2.contourf(x, y, z, n_levels)
fig2.colorbar(a)
[m,n]=np.where(z > 0.5)
z1=np.zeros(z.shape)
z1[m,n]=99
cs = ax2.contour(x, y, z1,2,hatches=['','.'])
plt.show()enter code here

标签: pythonpython-3.xpython-2.7matplotlibstatistics

解决方案


使用contourf()适当的参数来获得有用的阴影图。请参阅下面的工作代码中的重要注释:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-3, 5, 150).reshape(1, -1)
y = np.linspace(-3, 5, 120).reshape(-1, 1)
z = np.cos(x) + np.sin(y)

x, y = x.flatten(), y.flatten()

fig2, ax2 = plt.subplots()
n_levels = 6
a = ax2.contourf(x, y, z, n_levels)

fig2.colorbar(a)
[m,n] = np.where(z > 0.5)

z1=np.zeros(z.shape)
z1[m, n] = 99

# use contourf() with proper hatch pattern and alpha value
cs = ax2.contourf(x, y, z1 ,3 , hatches=['', '..'],  alpha=0.25)

plt.show()

输出图:

在此处输入图像描述


推荐阅读