子图:tight_layout 改变图形大小 [英] Subplots: tight_layout changes figure size
问题描述
使用 tiny_layout(h_pad=-1) 更改两个子图之间的垂直距离会更改总图形大小.如何使用 tiny_layout 定义图形大小?
Changing the vertical distance between two subplot using tight_layout(h_pad=-1) changes the total figuresize. How can I define the figuresize using tight_layout?
代码如下:
#define figure
pl.figure(figsize=(10, 6.25))
ax1=subplot(211)
img=pl.imshow(np.random.random((10,50)), interpolation='none')
ax1.set_xticklabels(()) #hides the tickslabels of the first plot
subplot(212)
x=linspace(0,50)
pl.plot(x,x,'k-')
xlim( ax1.get_xlim() ) #same x-axis for both plots
结果如下:
如果我写
pl.tight_layout(h_pad=-2)
在最后一行,然后我明白了:
in the last line, then I get this:
正如你所看到的,这个数字更大......
As you can see, the figure is bigger...
推荐答案
您可以使用 GridSpec 对象来精确控制宽度和高度比例,如回答 在这个线程 和 此处记录.
You can use a GridSpec object to control precisely width and height ratios, as answered on this thread and documented here.
使用您的代码进行实验,我可以通过使用 height_ratio
将两倍的空间分配给上部子图并增加 h_pad
参数来生成您想要的内容到 tight_layout
调用.这听起来并不完全正确,但也许您可以进一步调整...
Experimenting with your code, I could produce something like what you want, by using a height_ratio
that assigns twice the space to the upper subplot, and increasing the h_pad
parameter to the tight_layout
call. This does not sound completely right, but maybe you can adjust this further ...
import numpy as np
from matplotlib.pyplot import *
import matplotlib.pyplot as pl
import matplotlib.gridspec as gridspec
#define figure
fig = pl.figure(figsize=(10, 6.25))
gs = gridspec.GridSpec(2, 1, height_ratios=[2,1])
ax1=subplot(gs[0])
img=pl.imshow(np.random.random((10,50)), interpolation='none')
ax1.set_xticklabels(()) #hides the tickslabels of the first plot
ax2=subplot(gs[1])
x=np.linspace(0,50)
ax2.plot(x,x,'k-')
xlim( ax1.get_xlim() ) #same x-axis for both plots
fig.tight_layout(h_pad=-5)
show()
还有其他问题,例如更正导入、添加 numpy 以及绘制到 ax2
而不是直接使用 pl
.我看到的输出是这样的:
There were other issues, like correcting the imports, adding numpy, and plotting to ax2
instead of directly with pl
. The output I see is this:
这篇关于子图:tight_layout 改变图形大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!