【问题标题】:Matplotlib: set_xlim and set_ylim not working for contourf in 3d plotMatplotlib:set_xlim 和 set_ylim 不适用于 3d 图中的轮廓
【发布时间】:2021-11-04 12:18:39
【问题描述】:

我想在 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()

图:

【问题讨论】:

  • NameError: name 'axes3d' is not defined 包括所有导入

标签: python numpy matplotlib data-visualization visualization


【解决方案1】:

您可以使用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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-20
    • 2014-11-21
    相关资源
    最近更新 更多