【问题标题】:Can one get the number of rows and columns from an instance of the Figure class from matplotlib?可以从 matplotlib 的 Figure 类的实例中获取行数和列数吗?
【发布时间】:2020-10-26 10:53:29
【问题描述】:

问题:

假设想在一个图中放置 4 个子图 - 可以是 4 行 1 列,也可以是 1 行 4 列。可以使用fig, axes = plt.subplots(nrows=..., ncols=...) 来初始化这个子图。但是,输入nrows=4, ncols=1 和输入nrows=1, ncols=4 都给出相同axes.shape=(4,) 的axes。既然这些形状都是一样的,那么matplotlib是如何确定图形的行数和列数的呢? 可以从fig 或axes 的实例中获取nrows 和ncols 吗?

MWE:

如果上面不清楚,可以运行下面的代码来创建这样一个子图(注意print语句):

import numpy as np
import matplotlib.pyplot as plt

## sample data
x = np.arange(10)
y1 = np.cos(x)
y2 = np.sin(x)
y3 = np.tan(x)
y4 = 1 / y3

## make easy to identify
labels = ('cos', 'sin', 'tan', r'$\frac{1}{tan}$')
facecolors = ('darkorange', 'steelblue', 'purple', 'green')

## initialize plot
# fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(12,7)) ## shape=(2,2)
fig, axes = plt.subplots(nrows=4, ncols=1, figsize=(12,7)) ## shape=(4,)
# fig, axes = plt.subplots(nrows=1, ncols=4, figsize=(12,7)) ## shape=(4,)

## verify shape of axes
print(axes.shape)

## create a plot
for ax, y, label, facecolor in zip(axes.ravel(), (y1, y2, y3, y4), labels, facecolors):
    ax.plot(x, y, label=label, color=facecolor)

## add legend
fig.subplots_adjust(bottom=0.2)
fig.legend(loc='lower center', mode='expand', fontsize=8, ncol=4)

## fig.nrows outputs AttributeError: 'Figure' object has no attribute 'nrows'.

## show and close
plt.show()
plt.close(fig)

different but related question 的答案提到使用以下解决方案 - 但它输出错误:

for f in fig.get_children():
    print(f.colNum, f.rowNum)

# AttributeError: 'Rectangle' object has no attribute 'colNum'

我想可以迭代 try-except 循环来做到这一点,但我想知道是否有更清洁的方法。

【问题讨论】:

    标签: python-3.x matplotlib grid-layout figure multiple-axes


    【解决方案1】:

    当您调用 plt.subplots() 时,matplotlib 使用 GridSpec 创建子图。除了用于创建初始轴的一个之外,图形本身还可以有多个 GridSpec,因此您无法从图形本身获取 GridSpec,但可以从轴中获取:

    fig, axes = plt.subplots(nrows=1, ncols=4) ## shape=(4,)
    gs = axes[0].get_gridspec()
    gs.nrows  # return  1
    gs.ncols  # returns 4
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-09-12
      • 2012-12-10
      • 2020-04-07
      相关资源
      最近更新 更多