Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/312.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 填充多边形|遮罩阵列外部,其中标记超出圆形边界?_Python_Matplotlib - Fatal编程技术网

Python 填充多边形|遮罩阵列外部,其中标记超出圆形边界?

Python 填充多边形|遮罩阵列外部,其中标记超出圆形边界?,python,matplotlib,Python,Matplotlib,我使用plot(x,y,'r')绘制一个红色圆圈。x和y是阵列,当配对为(x,y)并绘制时,所有点形成一条圆线 fill(x,y,'r')绘制一个用红色填充(或着色)的红色圆圈 如何使圆内部保持白色,但将圆外部填充到轴边界 我研究了如何使用fill\u-between(x\u数组,y1\u数组,y2\u数组,where)但是在稍微使用它之后,我认为这对我的x,y数组不起作用。我想在圆的外面和由轴边界定义的正方形的里面填充(),但我不认为填充()是有能力的…我确信我可以把它变成一个积分类型的问题,

我使用
plot(x,y,'r')
绘制一个红色圆圈。x和y是阵列,当配对为(x,y)并绘制时,所有点形成一条圆线

fill(x,y,'r')
绘制一个用红色填充(或着色)的红色圆圈

如何使圆内部保持白色,但将圆外部填充到轴边界

我研究了如何使用
fill\u-between(x\u数组,y1\u数组,y2\u数组,where)
但是在稍微使用它之后,我认为这对我的x,y数组不起作用。我想在圆的外面和由轴边界定义的正方形的里面填充(),但我不认为
填充(
)是有能力的…我确信我可以把它变成一个积分类型的问题,δx和δy都变为零,但我不愿意

如果有人看到我在
fill\u between()
中遗漏了什么,请告诉我

我真正需要做的就是屏蔽二维数组中的数字,这些数字位于用x和y创建的圆的边界之外,这样,当二维数组被视为彩色图或轮廓时,圆的内部将是图像,外部将是白色

这可以通过2D阵列的掩蔽技术来实现吗?例如,使用
屏蔽\u where()
?我还没有调查过,但是威尔

有什么想法吗?谢谢

编辑1:以下是我有权展示的东西,我认为可以解释我的问题

from pylab import *
from matplotlib.path import Path
from matplotlib.patches import PathPatch

f=Figure()
a=f.add_subplot(111)

# x,y,z are 2d arrays

# sometimes i plot a color plot
# im = a.pcolor(x,y,z)
a.pcolor(x,y,z)

# sometimes i plot a contour
a.contour(x,y,z)

# sometimes i plot both using a.hold(True)

# here is the masking part.
# sometimes i just want to see the boundary drawn without masking
# sometimes i want to see the boundary drawn with masking inside of the boundary
# sometimes i want to see the boundary drawn with masking outside of the boundary

# depending on the vectors that define x_bound and y_bound, sometimes the boundary
# is a circle, sometimes it is not.

path=Path(vpath)
patch=PathPatch(path,facecolor='none')
a.add_patch(patch) # just plots boundary if anything has been previously plotted on a
if ('I want to mask inside'):
    patch.set_facecolor('white') # masks(whitens) inside if pcolor is currently on a,
    # but if contour is on a, the contour part is not whitened out. 
else: # i want to mask outside 
    im.set_clip_path(patch) # masks outside only when im = a.pcolor(x,y,z)
    # the following commands don't update any masking but they don't produce errors?
    # patch.set_clip_on(True)
    # a.set_clip_on(True)
    # a.set_clip_path(patch)

a.show()
我真正需要做的就是戴上面具 输出二维数组中 位于该区域边界之外 用x和y创建的圆,这样 将二维阵列视为颜色时 圆内的绘图或等高线 将是图像,外部将是 他脸色发白

您有两个选择:

首先,可以对图像使用遮罩数组。这更复杂,但更安全。若要遮罩圆外的阵列,请从圆心生成距离贴图,并遮罩距离大于半径的位置

更简单的选择是在绘制图像后,使用im.set_clip_path()剪裁面片外的区域

看。不幸的是,根据我的经验,对于某些轴(非笛卡尔轴),这可能有点小故障。不过,在其他任何情况下,它都应该工作得很好

编辑:顺便说一句,绘制一个内部有孔的多边形。但是,如果您只想遮罩图像,最好使用上述两个选项中的任何一个

Edit2:只举一个简单的例子说明这两种方法

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches

def main():
    # Generate some random data
    nx, ny = 100, 100
    data = np.random.random((ny,nx))

    # Define a circle in the center of the data with a radius of 20 pixels
    radius = 20
    center_x = nx // 2
    center_y = ny // 2

    plot_masked(data, center_x, center_y, radius)
    plot_clipped(data, center_x, center_y, radius)
    plt.show()

def plot_masked(data, center_x, center_y, radius):
    """Plots the image masked outside of a circle using masked arrays"""
    # Calculate the distance from the center of the circle
    ny, nx = data.shape
    ix, iy = np.meshgrid(np.arange(nx), np.arange(ny))
    distance = np.sqrt((ix - center_x)**2 + (iy - center_y)**2)

    # Mask portions of the data array outside of the circle
    data = np.ma.masked_where(distance > radius, data)

    # Plot
    plt.figure()
    plt.imshow(data)
    plt.title('Masked Array')

def plot_clipped(data, center_x, center_y, radius):
    """Plots the image clipped outside of a circle by using a clip path"""
    fig = plt.figure()
    ax = fig.add_subplot(111)

    # Make a circle
    circ = patches.Circle((center_x, center_y), radius, facecolor='none')
    ax.add_patch(circ) # Plot the outline

    # Plot the clipped image
    im = ax.imshow(data, clip_path=circ, clip_on=True)

    plt.title('Clipped Array')

main()

编辑2:在原始打印上打印遮罩多边形: 这里有一些关于如何在当前绘图中绘制一个多边形的更多细节,该多边形遮罩了它之外的所有内容。显然,没有更好的方法来剪裁等高线图(反正我可以找到…)

注意:此答案使用MATLAB语法,因为问题最初是这样标记的。但是,即使在Python中使用matplotlib,即使语法略有不同,概念也应该是相同的

一个选项是创建一个多边形,该多边形看起来有一个洞,但实际上只有两条边环绕一个空白空间并相互接触。您可以通过创建一组围绕圆边缘跟踪的
x
y
坐标,然后从圆边缘跟踪到边界正方形的边缘,然后围绕该正方形的边缘跟踪并沿同一条线返回到圆边缘来实现此目的。下面是一个以原点为中心的单位圆和4×4正方形的示例:

theta = linspace(0,2*pi,100);      %# A vector of 100 angles from 0 to 2*pi
xCircle = cos(theta);              %# x coordinates for circle
yCircle = sin(theta);              %# y coordinates for circle
xSquare = [2 2 -2 -2 2 2];         %# x coordinates for square
ySquare = [0 -2 -2 2 2 0];         %# y coordinates for square
hp = fill([xCircle xSquare],...    %# Plot the filled polygon
          [yCircle ySquare],'r');
axis equal                         %# Make axes tick marks equal in size
下面是您应该看到的图形:

注意右边连接圆和正方形边缘的线。这是红色多边形的两条边相交并相互接触的地方。如果不希望边线可见,可以将其颜色更改为与多边形的填充颜色相同,如下所示:

set(hp,'EdgeColor','r');

当然,MATLAB有一种直接绘制带孔多边形的方法??再说一次,我似乎也找不到它。。。matplotlib是这样处理的:谢谢大家的想法。似乎最方便的方法是从path.path类制作一个补丁,并从那里开始工作,如上面的示例,或者使用set_clip_path()在其他答案中给出的示例。set_clip_路径看起来确实是我最好的选择,但是如果我想使用第一个选项,我会使用
MaskedArray()
method吗?@AmyS-yes,我添加了一个示例来展示两种方法。希望有帮助!谢谢你的额外服务,乔。有趣且有用,但对于我正在使用的当前应用程序,我的边界由两个向量定义,当两个向量成对时,有时形成一个圆,有时不形成。我使用了
pcolor()
,因为我的轴是由2个二维数组定义的,这些数组并不总是笛卡尔坐标的,我不知道如何使用
imshow()
处理它。幸运的是,
set\u clip\u plath(patch)
是一个属性。对于
pcolor()
,但不适用于
contour()
plot()
:(如果您仍然感兴趣,请看我问题上面的编辑1,看看我是否可以在不使用预定义pcolor的情况下向axis添加遮罩面片?@AmyS-请参阅添加的代码片段。它应该在当前绘图上绘制定义多边形之外的所有填充多边形。我认为有一种更干净的方法来剪裁轮廓,但家长没有。希望这能更好一点!@JoeKington我意识到这是一篇老文章,但我刚刚找到它,不得不感谢你提供了如此有用的代码片段!只希望这个问题和答案更容易找到……在找到你的问题和答案之前,我花了一段时间寻找解决方案。
set(hp,'EdgeColor','r');