Pyplot - 在3D子图之间共享轴

时间:2017-01-12 14:18:27

标签: matplotlib 3d axes

我正在尝试并排创建两个3D suplots,我可以轻松地在视觉上进行比较。我希望能够链接他们的轴,以便当我在pyplot的交互式图形中旋转,平移或缩放其中一个时,另一个将以相同的方式旋转,平移或缩放。 我试着告诉人物分享(xyz),就像我在2D情节中所做的那样,但他们并没有按照我的预期行事。他们似乎没有联系。有人可以帮忙吗?

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

# Twice as wide as it is tall.
fig = plt.figure(figsize=plt.figaspect(0.5))

#---- First subplot
ax1 = fig.add_subplot(1, 2, 1, projection='3d')
X = np.arange(-5, 5, 0.25)
Y = np.arange(-5, 5, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)
surf1 = ax1.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm,
                   linewidth=0, antialiased=False)
ax1.set_zlim3d(-1.01, 1.01)

#---- Second subplot that I want to share axis with first subplot
ax2 = fig.add_subplot(1, 2, 2, projection='3d',sharex = ax1,sharey = ax1,sharez = ax1)
surf2 = ax2.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm,
                   linewidth=0, antialiased=False)

plt.show()

1 个答案:

答案 0 :(得分:-1)

您可以直接使用此问题提供的答案:

在这里提供一个完整的解决方案:

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


# Twice as wide as it is tall.
fig = plt.figure(figsize=plt.figaspect(0.5))

#---- First subplot
ax1 = fig.add_subplot(1, 2, 1, projection='3d')
X = np.arange(-5, 5, 0.25)
Y = np.arange(-5, 5, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)
surf1 = ax1.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm,
                   linewidth=0, antialiased=False)
ax1.set_zlim3d(-1.01, 1.01)

#---- Second subplot that I want to share axis with first subplot
ax2 = fig.add_subplot(1, 2, 2, projection='3d')
surf2 = ax2.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm,
                   linewidth=0, antialiased=False)

def on_move(event):
    if event.inaxes == ax1:
        if ax1.button_pressed in ax1._rotate_btn:
            ax2.view_init(elev=ax1.elev, azim=ax1.azim)
        elif ax1.button_pressed in ax1._zoom_btn:
            ax2.set_xlim3d(ax1.get_xlim3d())
            ax2.set_ylim3d(ax1.get_ylim3d())
            ax2.set_zlim3d(ax1.get_zlim3d())
    elif event.inaxes == ax2:
        if ax2.button_pressed in ax2._rotate_btn:
            ax1.view_init(elev=ax2.elev, azim=ax2.azim)
        elif ax2.button_pressed in ax2._zoom_btn:
            ax1.set_xlim3d(ax2.get_xlim3d())
            ax1.set_ylim3d(ax2.get_ylim3d())
            ax1.set_zlim3d(ax2.get_zlim3d())
    else:
        return
    fig.canvas.draw_idle()

c1 = fig.canvas.mpl_connect('motion_notify_event', on_move)

plt.show()