如何确定 matplotlib 轴对象的投影(2D 或 3D)?
How to determine the projection (2D or 3D) of a matplotlib axes object?
在 Python 的 matplotlib 库中,很容易在创建时指定轴对象的投影:
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
ax = plt.axes(projection='3d')
但是如何确定现有坐标区对象的投影?没有 ax.get_projection
,ax.properties
不包含 "projection" 键,快速 google 搜索没有找到任何有用的东西。
我认为没有自动化的方法,但显然有一些只有 3D 投影才有的属性(例如 zlim
)。
所以你可以写一个小辅助函数来测试它是否是 3D:
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)
打印:
ax1: 2
ax2: 3
原来这里给出的答案其实是对这道题比较好的答案:python check if figure is 2d or 3d
我在那个副本中提供的答案是对这个问题的更好答案。
在任何情况下,您都可以使用轴的 name
。这是确定投影的字符串。
plt.gca().name or ax.name
如果 ax
是轴。
3D 轴的名称将为 "3d"
。二维轴的名称将是 "rectilinear"
、"polar"
或其他名称,具体取决于绘图的类型。自定义投影将具有其自定义名称。
所以不用 ax.get_projection()
就用 ax.name
.
根据投影,ax
将是不同的 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
isinstance(ax1, Axes3D) # True - Axes3D is also a plt.Axes
在 Python 的 matplotlib 库中,很容易在创建时指定轴对象的投影:
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
ax = plt.axes(projection='3d')
但是如何确定现有坐标区对象的投影?没有 ax.get_projection
,ax.properties
不包含 "projection" 键,快速 google 搜索没有找到任何有用的东西。
我认为没有自动化的方法,但显然有一些只有 3D 投影才有的属性(例如 zlim
)。
所以你可以写一个小辅助函数来测试它是否是 3D:
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)
打印:
ax1: 2
ax2: 3
原来这里给出的答案其实是对这道题比较好的答案:python check if figure is 2d or 3d 我在那个副本中提供的答案是对这个问题的更好答案。
在任何情况下,您都可以使用轴的 name
。这是确定投影的字符串。
plt.gca().name or ax.name
如果 ax
是轴。
3D 轴的名称将为 "3d"
。二维轴的名称将是 "rectilinear"
、"polar"
或其他名称,具体取决于绘图的类型。自定义投影将具有其自定义名称。
所以不用 ax.get_projection()
就用 ax.name
.
根据投影,ax
将是不同的 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
isinstance(ax1, Axes3D) # True - Axes3D is also a plt.Axes