设置大小相同的子图(或gridspec) [英] Set subplot(or gridspec) with same size

查看:355
本文介绍了设置大小相同的子图(或gridspec)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用gridspec绘制两个图形:

fig = plt.figure(num=2,figsize=(5,2))
gs = gridspec.GridSpec(1, 2, width_ratios=[1,1])
ax0 = plt.subplot(gs[0])
ax1 = plt.subplot(gs[1])

ax0.imshow(ROI,'gray')

map1 = ax1.imshow(z,cmap=cm.YlOrRd)
divider1 = make_axes_locatable(ax1)  
cax1 = divider1.append_axes("right", size="5%", pad=0.05)
cbar1 = plt.colorbar(map1, cax=cax1)

ROIz被预定义为相同的大小. 但是它们的尺寸略有不同.

ROI and z are pre-defined with the same size. But they resutl in slightly different sizes.

我要使其具有相同的尺寸:

I want to make it as a same size:

如何解决?

推荐答案

问题是您将两个图形的宽度固定为gridspec,然后将颜色栏添加到第二个绘图中,该绘图占用了一些内容.宽度的5%(加上填充).由于imshow的纵横比为1:1,因此宽度的变化也会改变图形的高度.

The problem is that you fix the width of the two figures to be the same in gridspec and then add the colorbar to the second plot which takes up some of the width (5% plus the padding). And as imshow has an 1:1 aspect ration this change of width also changes the height of the figure.

避免这种情况的最简单方法是在宽度比例中考虑颜色条的额外宽度:

The simplest way to avoid that is to account for the additional width of the colorbar in the width ratio:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from mpl_toolkits.axes_grid1 import make_axes_locatable

# Random test data:
ROI = np.random.rand(250, 150)
z = np.random.rand(250, 150)

fig = plt.figure(num=2,figsize=(4,2))
gs = gridspec.GridSpec(1, 2, width_ratios=[1,1.08])
ax0 = plt.subplot(gs[0])
ax1 = plt.subplot(gs[1])

ax0.imshow(ROI,'gray')

map1 = ax1.imshow(z,cmap=plt.cm.YlOrRd)
divider1 = make_axes_locatable(ax1)
cax1 = divider1.append_axes("right", size="5%", pad="3%")
cbar1 = plt.colorbar(map1, cax=cax1)

plt.show()

这将导致以下绘图:

您也可以通过使用gridspec为色条添加第三个轴来避免这种情况:

You can also avoid that by simply adding a third axes for the colorbar using gridspec:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

# Random test data:
ROI = np.random.rand(250, 150)
z = np.random.rand(250, 150)

fig = plt.figure(num=2,figsize=(5,2))
gs = gridspec.GridSpec(1, 3, width_ratios=[1,1,0.05])
ax0 = plt.subplot(gs[0])
ax1 = plt.subplot(gs[1])
cax1 = plt.subplot(gs[2])

ax0.imshow(ROI,'gray')
map1 = ax1.imshow(z,cmap=plt.cm.YlOrRd)
cbar1 = plt.colorbar(map1, cax=cax1)

plt.show()

这给出了:

这可能更灵活,但也需要对填充和大小进行更多调整.

This is probably more flexible but also requires more tweaking of padding and sizes on your part.

这篇关于设置大小相同的子图(或gridspec)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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