【问题标题】:Matplotlib contour hatching not working if only two levels was used如果仅使用两个级别,则 Matplotlib 轮廓孵化不起作用
【发布时间】:2019-08-03 15:15:24
【问题描述】:

我正在尝试在等高线上绘制阴影 根据here 找到的示例统计某些标准。然而,我得到了规则的轮廓(黄线)而不是阴影。任何想法如何解决这个问题。谢谢

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

【问题讨论】:

    标签: python python-3.x python-2.7 matplotlib statistics


    【解决方案1】:

    使用 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()
    

    输出图:

    【讨论】:

    • 非常感谢。我想知道为什么我们需要将级别数设置为 3。我发现如果我将级别数设置为 1 但不能使用等于 2 的级别数,它也可以工作。知道是什么原因造成的。
    • 实际上如果你使用hatches=['|', '-', '.', '..','//','\\'],从1到5的任何级别都会在地块上产生阴影。在 hatches 列表中包含空白引号 ('') 作为一项,指定在相关轮廓范围内不需要阴影,因此在您发现的某些情况下它不会导致阴影。
    • 谢谢。我添加了以下两行,为轮廓集 artists, labels = cs.legend_elements() ax2.legend(artists, labels, handleheight=2) 创建了一个图例,现在我可以看到阴影表示哪些值。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-07
    • 1970-01-01
    • 2012-07-12
    • 2016-12-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多