仅使用matplotlib在圆圈内绘制绘图

时间:2018-04-30 11:51:33

标签: python numpy matplotlib interpolation draw

我有分散的数据,我正在将其插入到网格数据中。然后我用contourf函数绘制所有东西。最后,我只想在定义的圆圈内绘制所有内容。其他一切都应该是白色的,但我不知道如何实现这一点。有一种简单的方法可以做到这一点吗?

这是我的代码:

import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import griddata


def func(x, y):
  return x*(1-x)*np.cos(4*np.pi*x) * np.sin(4*np.pi*y**2)**2

grid_x, grid_y = np.mgrid[0:1:100j, 0:1:200j]

points = np.random.rand(1000, 2)
values = func(points[:,0], points[:,1])


grid_z0 = griddata(points, values, (grid_x, grid_y), method='nearest')

plt.contourf(grid_x,grid_y,grid_z0)

plt.savefig("plot_data_in_circle.png")

编辑:我附上了我的代码中出现的情节: picture produced by the current code

这就是它应该是这样的:

.

1 个答案:

答案 0 :(得分:2)

这可以通过创建Circle补丁,然后将其设置为clip_path来完成。

要使用clip_path,通常会存储要应用裁剪的艺术家,然后使用.set_clip_path。在这种情况下,由于您使用的是contourf,因此没有方法.set_clip_path,因此我们必须迭代与contourf返回的PathCollections一起存储的QuadContourSet },并使用set_clip_path method设置每个剪辑路径。

import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import griddata
import matplotlib.patches as patches

def func(x, y):
  return x*(1-x)*np.cos(4*np.pi*x) * np.sin(4*np.pi*y**2)**2

grid_x, grid_y = np.mgrid[0:1:100j, 0:1:200j]

points = np.random.rand(1000, 2)
values = func(points[:,0], points[:,1])


grid_z0 = griddata(points, values, (grid_x, grid_y), method='nearest')

fig, ax = plt.subplots()
cs = ax.contourf(grid_x,grid_y,grid_z0)

circ = patches.Circle((0.6, 0.4), 0.3, transform=ax.transData)
for coll in cs.collections:
    coll.set_clip_path(circ)

plt.show()

enter image description here

相关问题