如何将gridspec与plt.subplots()结合使用以消除子图行之间的空间 [英] How to combine gridspec with plt.subplots() to eliminate space between rows of subplots

查看:698
本文介绍了如何将gridspec与plt.subplots()结合使用以消除子图行之间的空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在子图中绘制多个图像,并消除子图中的空间(水平和垂直)或对其进行控制.我尝试在如何使用GridSpec ... 中使用该建议.我也在这里尝试过,但是他们没有使用subplots():子图之间的空间 通过下面的代码,我可以消除水平空间,而不能消除垂直空间.请不要将其标记为重复项,因为我已经尝试了其他帖子,但它们不执行我想要的操作.我的代码如下所示.也许在gridspec_kw词典中需要另一个关键字参数吗? 我想为此使用plt.subplots()而不是plt.subplot().万一重要,图像不是正方形,而是矩形.我还尝试在plt.show()之前添加f.tight_layout(h_pad=0,w_pad=0),但它没有任何改变.

I am trying to plot multiple images in subplots and either eliminate the space between subplots (horizontal and vertical) or control it. I tried to use the suggestion in How to Use GridSpec.... I also tried here but they are not using subplots(): space between subplots I am able to eliminate the horizontal space but not the vertical space with what I am doing in the code below. Please do not mark as duplicate as I have tried the other posts and they do not do what I want. My code is shown below. Maybe there is another keyword argument that I need in the gridspec_kw dictionary? I want to use plt.subplots() not plt.subplot() for this. In case it matters, the images are not square they are rectangular. I also tried adding f.tight_layout(h_pad=0,w_pad=0) before plt.show() but it did not change anything.

def plot_image_array_with_angles(img_array,correct_angles,predict_angles,
                              fontsize=10,figsize=(8,8)):
'''
Imports:
    import matplotlib.gridspec as gridspec
    import numpy as np
    import matplotlib.pyplot as plt
'''
num_images = len(img_array)
grid = int(np.sqrt(num_images))  # will only show all images if square
#f, axarr = plt.subplots(grid,grid,figsize=figsize)
f, axarr = plt.subplots(grid,grid,figsize=figsize,
                      gridspec_kw={'wspace':0,'hspace':0})
im = 0
for row in range(grid):
    for col in range(grid):
        axarr[row,col].imshow(img_array[im])
        title = 'cor = ' + str(correct_angles[im]) + '  pred = ' + str(predict_angles[im])
        axarr[row,col].set_title(title,fontsize=fontsize)
        axarr[row,col].axis('off')  # turns off all ticks
        #axarr[row,col].set_aspect('equal')
        im += 1
plt.show()
return

推荐答案

imshow图的纵横比会自动设置为使图像中的像素平方.此设置比任何subplots_adjustgridspec间距设置都要强.换句话说,如果子图的纵横比设置为"equal",则无法直接控制子图之间的间距.

The aspect ratio of an imshow plot is automatically set such that pixels in the image are squared. This setting is stronger than any of the subplots_adjust or gridspec settings for spacing. Or in other words you cannot directly control the spacing between subplots if those subplots have their aspect set to "equal".

第一个明显的解决方案是将图像宽高比设置为自动ax.set_aspect("auto").这解决了子图间距的问题,但是使图像失真.

First obvious solution is to set the image aspect to automatic ax.set_aspect("auto"). This solves the problem of subplot spacing, but distorts the images.

另一种选择是调整图形边距和图形大小,以使子图之间的间距符合要求.

The other option is to adjust the figure margins and the figure size such that the spacing between the subplots is as desired.

假设fighfigw是图形的高度和宽度(以英寸为单位),以及s子图宽度(以英寸为单位).边距为bottomtopleftright(相对于图形尺寸),垂直方向上的间距hspace,水平方向上的间距wspace(相对于子图尺寸).行数表示为n,列数表示为m. aspect是子图(图像)的高度和宽度(aspect = image height / image width)之间的比率.

Let's say figh and figw are the figure height and width in inch, and s the subplot width in inch. The margins are bottom, top, left and right (relative to figure size) and the spacings hspace in vertical and wspace in horizontal direction (relative to subplot size). The number of rows is denoted n and the number of columns m. The aspect is the ratio between subplot (image) height and width (aspect = image height / image width).

然后可以通过

fig, axes = plt.subplots(nrows=n, ncols=m, figsize=(figwidth, figheight))
plt.subplots_adjust(top=top, bottom=bottom, left=left, right=right, 
                        wspace=wspace, hspace=hspace)

可以根据以下各项计算相应的值:

The respective values can be calculated according to:

或者,如果边距相同:

一个例子:

import matplotlib.pyplot as plt

image = plt.imread("https://i.stack.imgur.com/9qe6z.png")
aspect = image.shape[0]/float(image.shape[1])
print aspect
n = 2 # number of rows
m = 4 # numberof columns
bottom = 0.1; left=0.05
top=1.-bottom; right = 1.-left
fisasp = (1-bottom-(1-top))/float( 1-left-(1-right) )
#widthspace, relative to subplot size
wspace=0.15  # set to zero for no spacing
hspace=wspace/float(aspect)
#fix the figure height
figheight= 3 # inch
figwidth = (m + (m-1)*wspace)/float((n+(n-1)*hspace)*aspect)*figheight*fisasp

fig, axes = plt.subplots(nrows=n, ncols=m, figsize=(figwidth, figheight))
plt.subplots_adjust(top=top, bottom=bottom, left=left, right=right, 
                    wspace=wspace, hspace=hspace)

for ax in axes.flatten():
    ax.imshow(image)
    ax.set_title("title",fontsize=10)
    ax.axis('off')

plt.show()

这篇关于如何将gridspec与plt.subplots()结合使用以消除子图行之间的空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆