Search code examples
pythonmatplotlib3d2dprojection

How to determine the projection (2D or 3D) of a matplotlib axes object?


In Python's matplotlib library it is easy to specify the projection of an axes object on creation:

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
ax = plt.axes(projection='3d')

But how do I determine the projection of an existing axes object? There's no ax.get_projection, ax.properties contains no "projection" key, and a quick google search hasn't turned up anything useful.


Solution

  • I don't think there is an automated way, but there are obviously some properties that only the 3D projection has (e.g. zlim).

    So you could write a little helper function to test if its 3D or not:

    from mpl_toolkits.mplot3d import Axes3D
    import matplotlib.pyplot as plt
    
    def axesDimensions(ax):
        if hasattr(ax, 'get_zlim'): 
            return 3
        else:
            return 2
    
    
    fig = plt.figure()
    
    ax1 = fig.add_subplot(211)
    ax2 = fig.add_subplot(212, projection='3d')
    
    print "ax1: ", axesDimensions(ax1)
    print "ax2: ", axesDimensions(ax2)
    

    Which prints:

    ax1:  2
    ax2:  3