缩小轴长度,同时在3D绘图中保持相等的纵横比

时间:2018-02-22 21:07:46

标签: python matplotlib plot mplot3d

我正在尝试在python中并排创建一个三维绘图和一个二维绘图。我需要两个图的宽高比相等,我使用此答案提供的代码管理:https://stackoverflow.com/a/31364297/125507。我现在遇到的问题是如何有效地" crop"三维图表因此它不会占用太多的空白区域。也就是说,我希望减小X轴和Y轴的长度,同时保持与(较长的)Z轴相等的比例。这是一个示例代码和图:

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

def set_axes_equal(ax):
    '''Make axes of 3D plot have equal scale so that spheres appear as spheres,
    cubes as cubes, etc..  This is one possible solution to Matplotlib's
    ax.set_aspect('equal') and ax.axis('equal') not working for 3D.

    Input
      ax: a matplotlib axis, e.g., as output from plt.gca().
    '''

    x_limits = ax.get_xlim3d()
    y_limits = ax.get_ylim3d()
    z_limits = ax.get_zlim3d()

    x_range = abs(x_limits[1] - x_limits[0])
    x_middle = np.mean(x_limits)
    y_range = abs(y_limits[1] - y_limits[0])
    y_middle = np.mean(y_limits)
    z_range = abs(z_limits[1] - z_limits[0])
    z_middle = np.mean(z_limits)

    # The plot bounding box is a sphere in the sense of the infinity
    # norm, hence I call half the max range the plot radius.
    plot_radius = 0.5*max([x_range, y_range, z_range])

    ax.set_xlim3d([x_middle - plot_radius, x_middle + plot_radius])
    ax.set_ylim3d([y_middle - plot_radius, y_middle + plot_radius])
    ax.set_zlim3d([z_middle - plot_radius, z_middle + plot_radius])

ax  = [None]*2
fig = plt.figure()
ax[0] = fig.add_subplot(121, projection='3d', aspect='equal')
ax[1] = fig.add_subplot(122, aspect='equal')



nn   = 30
phis = np.linspace(0,np.pi,  nn).reshape(1,nn)
psis = np.linspace(0,np.pi*2,nn).reshape(nn,1)
ones = np.ones((nn,1))
el_h = np.linspace(-5, 5, nn).reshape(1,nn)

x_sph = np.sin(phis)*np.cos(psis)
y_sph = np.sin(phis)*np.sin(psis)
z_sph = np.cos(phis)*ones

x_elp = np.sin(phis)*np.cos(psis)*.25
y_elp = np.sin(phis)*np.sin(psis)*.25
z_elp = el_h*ones

ax[0].scatter(x_sph, y_sph, z_sph)
ax[0].scatter(x_elp, y_elp, z_elp)
ax[1].scatter(y_sph, z_sph)
ax[1].scatter(y_elp, z_elp)

for ii in range(2):
    ax[ii].set_xlabel('X')
    ax[ii].set_ylabel('Y')
ax[0].set_zlabel('Z')

set_axes_equal(ax[0])
plt.savefig('SphereElipse.png', dpi=300)

这是它的图像输出: 3-D and 2-D sphere and ellipse side-by-side

显然,2D绘图会自动修改轴的长度,同时保持刻度,但3D绘图不会导致微小的表示,不能很好地利用分配给其子图的空间。有没有办法做到这一点?这个问题类似于之前未回答的问题How do I crop an Axes3D plot with square aspect ratio?,除了它增加了多个子图的规定,这意味着那里提供的答案不起作用。

0 个答案:

没有答案