Matplotlib:set_xlim 和 set_ylim 不适用于 3d 图中的 contourf

Matplotlib: set_xlim and set_ylim not working for contourf in 3d plot

我想在 3d 中创建一个 2d 切片轮廓图,其 x 和 y 的范围大于给定的 xlim 和 ylim。但是,当我设置 xlim 和 ylim 时,轮廓似乎延伸到了轴之外。如果有一种方法可以限制轴内的轮廓,我将不胜感激。

from matplotlib import cm
from mpl_toolkits.mplot3d import axes3d
import numpy as np

ax = plt.figure().add_subplot(projection='3d')
X, Y, Z = axes3d.get_test_data(0.05)

# Plot the 3D surface
#ax.plot_surface(X, Y, Z, rstride=8, cstride=8, alpha=0.3)

# Plot projections of the contours for each dimension.  By choosing offsets
# that match the appropriate axes limits, the projected contours will sit on
# the 'walls' of the graph
cset = ax.contourf(X, Y, Z, zdir='z', offset=-100, cmap=cm.coolwarm)

ax.set_xlim(-20, 20)
ax.set_ylim(-20, 20)
ax.set_zlim(-100, 100)

ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')

plt.show()

图:

您可以使用 numpy.where 过滤 Z:

Z = np.where((X > 20) | (X < -20), None, Z)
Z = np.where((Y > 20) | (Y < -20), None, Z)

示例:

import matplotlib.pyplot as plt
from matplotlib import cm
from mpl_toolkits.mplot3d import axes3d
import numpy as np

ax = plt.figure().add_subplot(projection='3d')
X, Y, Z = axes3d.get_test_data(0.05)

Z = np.where((X > 20) | (X < -20), None, Z)
Z = np.where((Y > 20) | (Y < -20), None, Z)

# Plot the 3D surface
#ax.plot_surface(X, Y, Z, rstride=8, cstride=8, alpha=0.3)

# Plot projections of the contours for each dimension.  By choosing offsets
# that match the appropriate axes limits, the projected contours will sit on
# the 'walls' of the graph
cset = ax.contourf(X, Y, Z, zdir='z', offset=-100, cmap=cm.coolwarm)

ax.set_xlim(-20, 20)
ax.set_ylim(-20, 20)
ax.set_zlim(-100, 100)

ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')

plt.show()