Skip to main content
 首页 » 编程设计

python之Matplotlib 忽略 3D 图中的负值

2025年02月15日8lonelyxmas

我必须绘制一个具有无意义负值的 3d 函数(它们不应出现在图中)。必须绘制的函数如下:

def constraint_function(x, y): 
    return min( 
        (1800 - 0.3 * x - 0.5 * y) / 0.4, 
        (500 - 0.1 * x - 0.08 * y) / 0.12, 
        (200 - 0.06 * x - 0.04 * y) / 0.05 
    ) 

我正在按以下方式计算函数:

xs = np.linspace(0, 3600, 1000) 
ys = np.linspace(0, 3600, 1000) 
zs = np.empty(shape=(1000, 1000)) 
for ix, x in enumerate(xs): 
    for iy, y in enumerate(ys): 
        zs[ix][iy] = constraint_function(x, y) 
xs, ys = np.meshgrid(xs, ys) 

该函数的有效值主要在正方形 [0, 3600]x[0, 3600] 中。我采用的第一种方法是设置轴限制以满足我的需要:

fig = plt.figure() 
 
ax = fig.add_subplot(111, projection='3d') 
ax.azim = 20 
ax.set_xlim(0, 3500) 
ax.set_ylim(0, 3500) 
ax.set_zlim(0, 4500) 
ax.plot_surface(xs, ys, zs) 
 
plt.show() 

结果如下图:

它只是忽略了限制并确实绘制了它。第二种方法是将负值定义为 np.nan 将函数更改为:

def constraint_function(x, y): 
    temp = min( 
        (1800 - 0.3 * x - 0.5 * y) / 0.4, 
        (500 - 0.1 * x - 0.08 * y) / 0.12, 
        (200 - 0.06 * x - 0.04 * y) / 0.05 
    ) 
    return temp if temp >= 0 else np.nan 

并将无效值的 alpha 设置为零:

plt.cm.jet.set_bad(alpha=0.0) 
ax.azim = 20 
ax.set_xlim(0, 3500) 
ax.set_ylim(0, 3500) 
ax.set_zlim(0, 4500) 
 
ax.plot_surface(xs, ys, zs) 
 
plt.show() 

它给我留下锯齿状的边框,这也是我不想要的。当绘图变为负值时,有没有办法摆脱这些边缘并获得平滑的线条?

请您参考如下方法:

首先,你的 z 值数组轴是颠倒的;它应该是 zs[iy][ix] 而不是 zs[ix][iy]。因此,您的情节会左右翻转。

其次,在 Python 中通过迭代构建 z 数组要慢得多;你应该像这样委托(delegate)给 numpy:

import numpy as np 
from mpl_toolkits.mplot3d import Axes3D 
import matplotlib.pyplot as plt 
 
# create axis sample 
xs = np.linspace(0, 3600, 1000) 
ys = np.linspace(0, 3600, 1000) 
 
# create mesh samples 
xxs, yys = np.meshgrid(xs, ys) 
 
# create data 
zzs = np.min([ 
    ((1800 - 0.30 * xxs - 0.50 * yys) / 0.40), 
    (( 500 - 0.10 * xxs - 0.08 * yys) / 0.12), 
    (( 200 - 0.06 * xxs - 0.04 * yys) / 0.05) 
], axis=0) 
 
# clip data which is below 0.0 
zzs[zzs < 0.] = np.NaN 

NumPy 向量化运算快很多倍。

第三,除了采样分辨率太低外,您的代码没有什么特别的问题;设置得更高,

fig = plt.figure() 
ax = fig.add_subplot(111, projection='3d') 
ax.azim = 20 
ax.set_xlim(0, 3500) 
ax.set_ylim(0, 3500) 
ax.set_zlim(0, 4500) 
ax.plot_surface(xxs, yys, zzs, rcount=200, ccount=200) 
 
plt.show() 

产生