Search code examples
pythonplotaxes

Same range for axes x y z


I have an array with values (0.7, 0.4, 0.1) and I would like to plot the corresponding ellipsoid with this code:

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

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

u = np.linspace(0, 2 * np.pi, 100)
v = np.linspace(0, np.pi, 100)

x = 0.7 * np.outer(np.cos(u), np.sin(v))
y = 0.4 * np.outer(np.sin(u), np.sin(v))
z = 0.1 * np.outer(np.ones(np.size(u)), np.cos(v))
ax.plot_surface(x, y, z,  rstride=4, cstride=4, color='b')

plt.show()

When I plot the figure, it looks like a sphere more than the expected ellipsoid. I suppose the problem is setting the "correct" range for the axes.

How could I solve this "problem"?


Solution

  • You could set proper ranges with ax.set_xlim(), ax.set_ylim() and ax.set_zlim() methods.

    from mpl_toolkits.mplot3d import Axes3D
    import matplotlib.pyplot as plt
    import numpy as np
    
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    
    u = np.linspace(0, 2 * np.pi, 100)
    v = np.linspace(0, np.pi, 100)
    
    x = 0.7 * np.outer(np.cos(u), np.sin(v))
    y = 0.4 * np.outer(np.sin(u), np.sin(v))
    z = 0.1 * np.outer(np.ones(np.size(u)), np.cos(v))
    ax.plot_surface(x, y, z,  rstride=4, cstride=4, color='b')
    ax.set_xlim([-0.5, 0.5])
    ax.set_ylim([-0.5, 0.5])
    ax.set_zlim([-0.5, 0.5])
    
    plt.show()