You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Matplotlib仅在指定圆形区域内绘制插值后的等值填充图?

解决方法:只在圆形区域内显示contourf绘图

嘿,这个需求其实很好实现!这里有两种简单的方法,你可以根据自己的场景选择:

方法一:用掩码数组处理数据(推荐)

这种方法直接修改你的网格数据,把圆形区域外的值设为NaN,这样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

# 生成原始散点数据(模拟你的数据)
np.random.seed(123)
points = np.random.rand(1000, 2)
values = func(points[:,0], points[:,1])

# 定义插值网格
grid_x, grid_y = np.mgrid[0:1:100j, 0:1:100j]

# 插值得到网格数据
grid_z = griddata(points, values, (grid_x, grid_y), method='cubic')

# --- 核心:创建圆形掩码 ---
# 设置圆形中心和半径
circle_center = (0.5, 0.5)
circle_radius = 0.3

# 计算每个网格点到中心的距离
distances = np.sqrt((grid_x - circle_center[0])**2 + (grid_y - circle_center[1])**2)
# 创建掩码:距离大于半径的点设为True
mask = distances > circle_radius

# 将掩码区域的数据设为NaN
grid_z[mask] = np.nan

# 绘图
plt.figure(figsize=(6,6))
contour = plt.contourf(grid_x, grid_y, grid_z, levels=20, cmap='viridis')
plt.colorbar(contour)
plt.gca().set_aspect('equal')  # 保证圆形显示为正圆
plt.title('Contourf只在圆形区域显示(掩码法)')
plt.show()

关键说明

  • 先计算网格中每个点到圆形中心的距离,判断是否在圆外
  • 把圆外的grid_z值设为NaN,matplotlib的绘图函数会自动忽略NaN值,只绘制有效区域
  • 加上set_aspect('equal')可以确保圆形不会被拉伸变形

方法二:用Patch遮罩覆盖圆外区域

如果你不想修改原始数据,可以先绘制完整的contourf,再用白色的Patch把圆外的区域覆盖掉。

完整代码示例

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

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

# 生成原始散点数据、插值网格、网格数据(和方法一相同)
np.random.seed(123)
points = np.random.rand(1000, 2)
values = func(points[:,0], points[:,1])
grid_x, grid_y = np.mgrid[0:1:100j, 0:1:100j]
grid_z = griddata(points, values, (grid_x, grid_y), method='cubic')

# 绘图
plt.figure(figsize=(6,6))
contour = plt.contourf(grid_x, grid_y, grid_z, levels=20, cmap='viridis')
plt.colorbar(contour)
ax = plt.gca()
ax.set_aspect('equal')

# --- 核心:添加白色遮罩 ---
circle_center = (0.5, 0.5)
circle_radius = 0.3

# 1. 创建一个覆盖整个坐标轴的白色矩形
rect = Rectangle((0, 0), 1, 1, color='white')
# 2. 创建圆形路径,作为遮罩的反向区域
circle = Circle(circle_center, circle_radius)
# 3. 设置矩形的clip路径,只显示圆形之外的部分
rect.set_clip_path(circle, transform=ax.transData)
rect.set_clip_on(True)
# 4. 将矩形添加到坐标轴
ax.add_patch(rect)

plt.title('Contourf只在圆形区域显示(遮罩法)')
plt.show()

关键说明

  • 先绘制完整的contourf,再用白色矩形覆盖整个轴域
  • 通过set_clip_path让矩形只显示圆形之外的部分,从而把圆外的contourf内容遮掉
  • 这种方法不需要修改原始数据,适合需要保留完整数据的场景

内容的提问来源于stack exchange,提问作者Jan SE

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:46:13