定义 2 列 x 1 行子图的问题

Problems defining a 2 column x 1 row subplot

我在 Python 中设置 2 列 x 1 行子图配置时遇到问题。如果我转到 2 x 2 一切正常,但 2 x 1 似乎会降低行维度

简化代码如下,我想用两列 (nx) 制作 2 个图 (numplots)

import matplotlib
import matplotlib.pyplot as plt 

numplots = 2
nx = 2
ny = int(numplots/2)
if ny != numplots/2:
  ny += 1
fig, ax = plt.subplots(nrows=ny, ncols=nx )  
print(ax.shape, nx, ny)  

这段代码的结果如下;

(2,) 2 1

如您所见,ax 有一个空的第二维 - 为什么?

如果我将 numplots 更改为 3 或更大,ax 的形状就可以了

Matplotlib 在其实现中使用了 numpy。 Numpy 将形状为 (n, 1) 的数组视为简单向量,因此 (n,) 表示向量。它不应该对您的绘图代码的结果有任何影响。