【问题标题】:How to determine the projection (2D or 3D) of a matplotlib axes object?如何确定 matplotlib 轴对象的投影(2D 或 3D)?
【发布时间】:2017-01-12 23:49:42
【问题描述】:

在 Python 的 matplotlib 库中,很容易在创建时指定坐标区对象的投影:

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

但是如何确定现有坐标区对象的投影?没有ax.get_projectionax.properties 不包含“投影”键,快速谷歌搜索也没有发现任何有用的东西。

【问题讨论】:

    标签: python matplotlib 3d 2d projection


    【解决方案1】:

    根据投影,ax 将是不同的类。

    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
    

    【讨论】:

      【解决方案2】:

      原来这里给出的答案其实是对这个问题更好的答案:python check if figure is 2d or 3d 我在该副本中提供的答案是对这个问题的更好答案。

      在任何情况下,您都可以使用坐标区的name。这是确定投影的字符串。

      plt.gca().name  ax.name

      如果ax 是坐标轴。

      3D 轴的名称将是 "3d"。 2D 轴的名称将是 "rectilinear""polar" 或其他名称,具体取决于绘图类型。自定义投影将具有其自定义名称。

      所以不要使用ax.get_projection(),只需使用ax.name

      【讨论】:

      • 这可能是默认名称,但用户可以随时更改。
      【解决方案3】:

      我不认为有一种自动化的方式,但显然有些属性只有 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
      

      【讨论】:

      • 谢谢。我会接受这个答案,因为它可以解决问题,但我会继续寻找一种内置的方式来做到这一点。如果我发现任何问题,会更新我的问题。
      猜你喜欢
      • 2021-02-04
      • 2011-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-03
      • 1970-01-01
      • 2010-09-09
      相关资源
      最近更新 更多