Search code examples
pythonmatplotlibmatplotlib-3d

How can I hide an axis of a 3d plot


How can I make a 3D plot without showing the axes?

When plotting a 3d plot, Matplotlib not only draws the x, y, and z axes, it draws light gray grids on the x-y, y-z, and x-z planes. I would like to draw a "free-floating" 3D plot, with none of these elements.

Stuff I've tried:

# Doesn't work; this hides the plot, not the axes
my_3d_axes.set_visible(False)

# Doesn't do anything. Also, there's no get_zaxis() function.
my_3d_axes.get_xaxis().set_visible(False)
my_3d_axes.get_yaxis().set_visible(False)

Solution

  • ax.set_axis_off()

    Just to provide a concrete and direct example of what was mentioned at https://stackoverflow.com/a/7363931/895245

    #!/usr/bin/env python3
    
    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib.patches import Circle
    import mpl_toolkits.mplot3d.art3d as art3d
    
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    ax.set_axis_off()
    
    # Draw a circle on the x=0 'wall'
    p = Circle((0, 0), 1, fill=False)
    ax.add_patch(p)
    art3d.pathpatch_2d_to_3d(p, zdir="x")
    p = Circle((0, 0), 1, fill=False)
    ax.add_patch(p)
    art3d.pathpatch_2d_to_3d(p, zdir="z")
    
    ax.set_xlim(-1.2, 1.2)
    ax.set_ylim(-1.2, 1.2)
    ax.set_zlim(-1.2, 1.2)
    
    plt.savefig('main.png', format='png', bbox_inches='tight')
    

    Output:

    enter image description here

    Without ax.set_axis_off() it would look like:

    enter image description here

    You will notice however that this produces an excessively large whitespace margin around the figure as it simply hides the axes but does not change the viewbox. I tried bbox_inches='tight' and it did not help as it does in 2D. How to solve that at: Remove white spaces in Axes3d (matplotlib)

    Tested on matplotlib==3.2.2.