【问题标题】:how to distinguish axes between image, line plot and colorbar?如何区分图像、线图和颜色条之间的轴?
【发布时间】:2022-11-24 04:38:37
【问题描述】:

我正在尝试制作一个可以将多个图形排列为子图的通用函数。 我需要遍历子图以调整和统一某些属性(例如轴范围),我通过迭代 fig.axes 来做到这一点。

我在处理不同类型的图(可以在我的应用程序中混合使用)时遇到了一些麻烦,例如我可能想为图像和线图设置相同的 x 范围,但我不想为 colorbar 设置相同的 x 范围,所以:区分不同类型图的最佳方法是什么(以及其他类型的图)出现,例如作为子类)?

目前,我发现最好的方法是使用 try 和 except,并根据不同的属性进行选择,例如如果 len(ax.images) > 0 是图像图,但我找不到线条和颜色条之间的区别(两者都没有图像),无论如何,最好的方法是什么?

我尝试将它们与以下代码进行比较,该代码创建了三个轴 licb(分别为线条、图像、颜色条):

# create test figure
plt.figure()
b = np.arange(12).reshape([4,3])
plt.subplot(121)
plt.plot([1,2,3],[4,5,6])
plt.subplot(122)
plt.imshow(b)
plt.colorbar()

# create  test objects
ax=plt.gca()
fig=plt.gcf()
l,i,cb = fig.axes

# do a simple test, images are different:
for o in l,i,cb: print(len(o.images))

# this also doesn't work in finding properties not in common between lines and colobars, gives empty list.
[a for a in dir(l) if a not in dir(cb)]

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    我必须提醒你

    1. Matplotlib 为您提供了许多不同的容器对象,
    2. 您可以在使用时将 Axes 目标存储在列表或字典中 — 您甚至可以说 ax.ax_type = 'lineplot'

      也就是说,例如,

      from matplotlib.pyplot import subplots
      fig, ax = subplots()
      ax.plot((1, 2), (2, 1))
      axes_types = []
      for ax_i in [ax]:
          try:
              ax_i.__getattr__('get_clabel')
              axes_types.append('colorbar')
          except AttributeError:
              axes_types.append('lineplot')
      ...
      

      换句话说,选择一种方法,该方法对于您正在测试的每种不同类型都是唯一的,并检查它是否可用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-21
      • 1970-01-01
      • 2010-09-14
      • 2012-01-23
      相关资源
      最近更新 更多