Skip to main content
 首页 » 编程设计

python之修复 3D 图的锯齿状边缘,选择合适的掩码

2025年05月04日6webabcd

所以我有一些 3D 数据,除了边缘看起来参差不齐之外,我可以很好地绘制它们。

相关代码:

import numpy as np 
from matplotlib import cm 
from matplotlib import pyplot as plt 
from mpl_toolkits.mplot3d import Axes3D 
 
x = np.arange(-1, 1, 0.01) 
y = np.arange(-1, 1, 0.01) 
x, y = np.meshgrid(x, y) 
rho = np.sqrt(x**2 + y**2) 
 
# Attempts at masking shown here 
# My Mask 
row=0 
while row<np.shape(x)[0]: 
    col=0 
    while col<np.shape(x)[1]: 
        if rho[row][col] > 1: 
            rho[row][col] = None 
        col=col+1 
    row=row+1 
 
# Calculate & Plot 
z = rho**2 
fig = plt.figure() 
ax = fig.gca(projection='3d') 
surf = ax.plot_surface(x, y, z, rstride=8, cstride=8,  cmap=cm.bone, alpha=0.15, linewidth=0.25) 
plt.show() 

产生: Jagged Edges 这与我想要的非常接近,除了边缘是锯齿状的。

如果我在上面的代码中禁用我的掩码并将其替换为 rho = np.ma.masked_where(rho > 1, rho) 它给出: Single Liner Plot

它不是锯齿状的,但不是我想要的角落。

关于消除这种锯齿状的不同 mask 或绘图方法有什么建议吗?

请您参考如下方法:

您是否考虑过使用极坐标(如 this example )?

类似于:

import numpy as np 
from matplotlib import cm 
from matplotlib import pyplot as plt 
from mpl_toolkits.mplot3d import Axes3D 
 
# create supporting points in polar coordinates 
r = np.linspace(0,1.25,50) 
p = np.linspace(0,2*np.pi,50) 
R,P = np.meshgrid(r,p) 
# transform them to cartesian system 
x, y = R * np.cos(P), R * np.sin(P) 
 
rho = np.sqrt(x**2 + y**2) 
 
# Calculate & Plot 
z = rho**2 
fig = plt.figure() 
ax = fig.gca(projection='3d') 
surf = ax.plot_surface(x, y, z, rstride=1, cstride=1,  cmap=cm.bone, alpha=0.15, linewidth=0.25) 
plt.show()