binnev
binnev

Reputation: 1858

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.

Upvotes: 4

Views: 6360

Answers (3)

Mark Loyman
Mark Loyman

Reputation: 2170

Depending on the projection, ax will be a different class.

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

fig = plt.figure()
ax1 = fig.add_subplot(211)
ax2 = fig.add_subplot(212, projection='3d')

print(type(ax1))  # <class 'matplotlib.axes._subplots.AxesSubplot'>
print(type(ax2))  # <class 'matplotlib.axes._subplots.Axes3DSubplot'>

isinstance(ax1, plt.Axes)  # True
isinstance(ax1, Axes3D)    # False
isinstance(ax2, plt.Axes)  # True - Axes3D is also a plt.Axes
isinstance(ax2, Axes3D)    # True 

Upvotes: 2

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339220

It turns out that the answer given here is actually a better answer to this question: python check if figure is 2d or 3d And the answer i provided at that duplicate is a better answer to this question.

In any case, you can use the name of the axes. This is the string that determines the projection.

plt.gca().name   or   ax.name

if ax is the axes.

A 3D axes' name will be "3d". A 2D axes' name will be "rectilinear", "polar" or some other name depending on the type of plot. Custom projections will have their custom names.

So instead of ax.get_projection() just use ax.name.

Upvotes: 5

tmdavison
tmdavison

Reputation: 69116

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

Upvotes: 4

Related Questions