【问题标题】:Numpy and Matplotlib, Printing a matrix with imshow or pcolor ProblemNumpy 和 Matplotlib,使用 imshow 或 pcolor 打印矩阵问题
【发布时间】:2021-02-25 23:29:41
【问题描述】:

我有一个问题,问题文本是:

创建一个函数plot_list(Xs, n_per_row),它接受一个numpy二维数组列表和一个参数n_per_row来设置单行显示的元素数量。

与以下 4 个数组列表关联的输出应如下图所示。

plot_list(Xs, n_per_row=2)

Xs =[
[[1 0 0 0]
 [1 0 0 0]
 [0 0 0 0]
 [0 0 0 0]]
,
[[0 0 0 0]
 [0 0 0 0]
 [0 1 0 0]
 [0 1 0 0]]
,
[[0 0 1 1]
 [0 0 0 0]
 [0 0 0 0]
 [0 0 0 0]]
,
[[0 0 0 0]
 [0 0 0 0]
 [0 0 0 0]
 [0 0 1 1]]
]

Xs=np.array(Xs)

应该输出类似的图像;

我写了如下函数

def plot_list(Xs, n_per_row=5):
    '''Takes an  input of 4 arrays only, n_per_row'''
    
    a= np.array(Xs)
    
    fig, axs = plt.subplots(nrows=a.shape[0]//n_per_row, ncols=n_per_row ,figsize=(10,10))

    for i, ax in enumerate(fig.axes):
        if a.ndim==3:
            ax.pcolormesh(a[i],cmap='Greys')
        elif a.ndim<3:
            ax.pcolormesh(a,cmap='Greys')
        ax.grid(True, lw=1)
        ax.set_ylim(ax.get_ylim()[::-1])
    
    plt.show()

当被称为plot_list(Xs, n_per_row=2)

产生以下输出(注意网格,没有按照我的意图对齐)

但是,当我调用该函数以在一行中产生 4 个结果而不是 2 个结果时,会出现以下可憎的情况; plot_list(Xs, n_per_row=4)

注意 y 轴是 8 个单位长,但 x 是 4。有人知道如何解决这个问题吗?网格对齐和X轴的缩短?

谢谢

【问题讨论】:

  • 您的 figsize 参数不能是静态的,否则它会尝试将 1x4 子图放入正方形图中,从而为您提供又高又窄的图。为了解决这个问题,我建议定义一个nRowsnCols 变量,然后将figsize=(5*nCols,5*nRows) 放入plt.subplots() 命令中

标签: python arrays numpy matplotlib matrix


【解决方案1】:

需要改进的地方很少:

  1. 根据布局改变图形大小
  2. 使用set_major_locator强制网格

从 matplotlib 导入ticker as mticker def plot_list(Xs, n_per_row=5): '''只接受4个数组的输入,n_per_row'''

a= np.array(Xs)

nrows = a.shape[0]//n_per_row

fig, axs = plt.subplots(nrows=nrows, ncols=n_per_row ,
                        figsize=(n_per_row*5,nrows*5))       # adjust the figsize here


for i, ax in enumerate(fig.axes):
    if a.ndim==3:
        ax.pcolormesh(a[i],cmap='Greys')
    elif a.ndim<3:
        ax.pcolormesh(a,cmap='Greys')
    ax.grid(True, lw=1)

    # set locator here
    ax.xaxis.set_major_locator(mticker.MultipleLocator(1))
    ax.yaxis.set_major_locator(mticker.MultipleLocator(1))
    ax.set_ylim(ax.get_ylim()[::-1])

    ax.set_aspect('equal')

plt.show()

然后输出:

plot_list(Xs, n_per_row=4) 给出:

【讨论】:

    猜你喜欢
    • 2022-01-18
    • 1970-01-01
    • 2020-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多