问题
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.
回答1:
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
回答2:
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.
来源:https://stackoverflow.com/questions/39333446/how-to-determine-the-projection-2d-or-3d-of-a-matplotlib-axes-object