Matplotlib 3D图,如何正确使用set_zlim()

时间:2019-06-02 01:23:01

标签: matplotlib

我有多个情节。我想将Z lim设置为仅显示指定范围内的曲线。我的代码在这里

# make 3d axes
fig = plt.figure()
ax = fig.gca(projection='3d')

# test data
x = np.arange(-1., 1., .1)
y = np.arange(-1., 1., .1)
z1 = x**2
z2 = x**3
z3 = x**4

# plot test data
ax.plot(x, np.ones(len(x)), z1)
ax.plot(x, np.ones(len(x))*3, z2)
ax.plot(x, np.ones(len(x))*5, z3)

# make labels
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
ax.set_zlim(0)
plt.show()

显示 enter image description here 我希望图形中仅显示Z2的正部分,但它会显示所有曲线并使图更混乱。

1 个答案:

答案 0 :(得分:0)

您可以在绘制之前使用MaskedArray过滤不需要的数据。解决方法如下:

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
import numpy.ma as ma

fig = plt.figure(figsize=[8,7])
ax = fig.gca(projection='3d')

# test data
x = np.arange(-1., 1., .1)
y = np.arange(-1., 1., .1)
z1 = x**2
z2 = x**3
z3 = x**4

# masking the data (take `z2` as the base)
z2m = ma.masked_less_equal(z2, 0, copy=True)
y2 = np.ones(len(x))*3

# applying the mask to corresponding `x` and `y`
x2m = ma.MaskedArray(x, mask=z2m.mask)
y2m = ma.MaskedArray(y2, mask=z2m.mask)

# we get (x2m, y2m, z2m) to plot

# plot test data
ax.plot(x, np.ones(len(x)), z1)
ax.plot(x, np.ones(len(x))*3, z2)
ax.scatter(x2m, y2m, z2m)    # plot the masked data as points
ax.plot(x, np.ones(len(x))*5, z3)

# make labels
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
ax.set_zlim(0)

# set view angles to get better plot
ax.azim = 220   # z rotation (default=270)
ax.elev = 2     # x rotation (default=0)
ax.dist = 10    # zoom (define perspective)
plt.show()

输出图:

enter image description here