我使用matplotlib绘制等高线图。在第二步中,我想从该图中提取一个小区域,并将其绘制在一个新的轴上。
我能找到的最接近的是一个裁剪图像的教程:https://matplotlib.org/3.1.0/gallery/images_contours_and_fields/image_clip_path.html
但我没有找到一种方法来从一个图形上裁剪一个补丁。
下面是创建轮廓图的代码:(基于本例:https://docs.scipy.org/doc/numpy/reference/generated/numpy.meshgrid.html )
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(-5, 5, 0.1)
y = np.arange(-5, 5, 0.1)
xx, yy = np.meshgrid(x, y, sparse=True)
z = np.sin(xx**2 + yy**2) / (xx**2 + yy**2)
h = plt.contourf(x,y,z)
plt.plot(-2, 2.5, 'or')
plt.show()
附加的图像1显示了我想要生成的图形类型:一个新图形,具有与原始图形相同的边界框,但只绘制了一个已知位置周围的小块。
发布于 2020-05-04 14:07:27
不显示z
中的NaN值。因此,您需要做的就是定义剪辑路径,然后确定哪些(x,y)值在该路径之外,并将相应的z
值设置为NaN。
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(-5, 5, 0.01) # need higher resolution to get nice clipping boundaries
y = np.arange(-5, 5, 0.01)
xx, yy = np.meshgrid(x, y) # need dense meshgrid for contains_points
z = np.sin(xx**2 + yy**2) / (xx**2 + yy**2)
patch = plt.Circle((-2, 2), 1) # circle with radius 1 around the point (-2, 2)
path = patch.get_path().transformed(patch.get_patch_transform()) # the path attribute of Circle has to be transformed to data units
is_valid = path.contains_points(np.c_[xx.ravel(), yy.ravel()]).reshape(xx.shape)
z[~is_valid] = np.nan # NaN values are not plotted
h = plt.contourf(xx,yy,z)
plt.plot(-2, 2.5, 'or')
plt.show()
https://stackoverflow.com/questions/61593531
复制相似问题