【问题标题】:Mask a specific area in contour plot?掩盖等高线图中的特定区域?
【发布时间】:2018-03-08 16:16:13
【问题描述】:

我想知道是否有人知道如何在 python 的等高线图中屏蔽或隐藏特定区域,这是我的代码的一部分

    self.fig=plt.figure()
    delta = 0.025
    xmin=4
    xmin=6
    x=np.arange(4,6,delta)
    ymin=85
    ymax=91
    y = np.arange(85, 91, delta)
    X, Y = np.meshgrid(x, y)
    Z=formel()//here im using a specific formula to calculate Z
    plt.gcf().subplots_adjust(left=0.16)
    plt.xlabel(xlabel)
    plt.ylabel(ylabel)
    self.CS = plt.contour(X, Y, Z)
    plt.xlim(xmin, xmax)
    plt.ylim(ymin, ymax)
    plt.plot(pointX, pointY, 'kx')
    plt.clabel(self.CS, inline=1, fontsize=10)
    self.canvas = FigureCanvasTkAgg(self.fig, self)
    self.canvas.get_tk_widget().config(width=400,height=400)`

这就是我想要掩盖这些区域的方式 谢谢各位

【问题讨论】:

  • 请调整您的问题以获得 MCVE,因为目前代码 sn-p 不会运行,因为缺少很多东西(例如 formel,x,y 和 @987654327 @)。
  • 我编辑了这个问题,但我没有写formel,因为它很长,在这里没有任何意义。希望这就是您要求编辑问题时的意思。

标签: python matplotlib tkinter


【解决方案1】:

您可以使用PathPatch 在顶部显示您的面具,如下所示:

import numpy as np
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
import matplotlib.path as mpath

ax = plt.gca()

x = np.linspace(0.04, 0.06, 100)
y = np.random.random(100) * [0.91 - 0.85] + 0.85

top, right, bottom, left = y.max(), x.max(), y.min(), x.min()
mask_height = (top - bottom) * 0.4      # 40% mask coverage

plt.plot(x, y, zorder=1)

ax.set_xlim(left, right)
ax.set_ylim(bottom, top)

path_data = [
    (mpath.Path.MOVETO, (left, bottom)),
    (mpath.Path.LINETO, (right, bottom)),
    (mpath.Path.LINETO, (left, mask_height + bottom)),
    (mpath.Path.CLOSEPOLY, (0,0)),

    (mpath.Path.MOVETO, (right , top)),
    (mpath.Path.LINETO, (right, top - mask_height)),
    (mpath.Path.LINETO, (left, top)),
    (mpath.Path.CLOSEPOLY, (0, 0)),
    ]

codes, verts = zip(*path_data)
path = mpath.Path(verts, codes)
patch = mpatches.PathPatch(path, facecolor=(0.8, 0.8, 0.8), lw=2, ec=(0.8, 0.8, 0.8), zorder=2)#, alpha=0.5)
ax.add_patch(patch)
plt.show()

这会给你类似的东西:

【讨论】:

  • 谢谢你的建议,我去试试看。
  • 我已将其更新为根据数据自动计算path_data
  • 嘿,我得到一个错误,说'int'对象不可调用
  • 您是在“按原样”测试我的脚本,还是进行了更改?它应该可以正常工作。
  • 不,我实际上改变了一点,我现在就试试吧
猜你喜欢
  • 2023-04-06
  • 2015-08-28
  • 2016-03-13
  • 2020-07-30
  • 2023-03-18
  • 2013-08-25
  • 1970-01-01
  • 2017-11-17
  • 2013-10-19
相关资源
最近更新 更多