子图 imshow 和图共享相同的维度 [英] Subplot imshow and plot sharing same dimensions
问题描述
我有两个子图,一个 ax1.imshow
和一个 ax2.plot
.我希望 imshow
保留其原始纵横比,并且我希望 plot
与 imshow
具有相同的高度.另外,我希望两个子图之间没有间隙,这意味着两个黑色边框应该彼此相邻或重叠.
I have two subplots, an ax1.imshow
and a ax2.plot
. I want the imshow
to retain its original aspect ratio, and I want the plot
to have the same height as the imshow
. In addition I want there to be no gap between the two subplots, meaning the two black borders should be right next to eachother or overlap.
import numpy as np
import matplotlib.pyplot as plt
fig, (ax1,ax2) = plt.subplots(1,2)
ax1.imshow(np.random.random((100,100)))
ax2.plot(np.random.random((100)))
ax2.yaxis.tick_right()
fig.tight_layout(pad=0.0)
fig.savefig("test.png")
给出结果
我基本上希望右子图具有与左子图相同的高度(并对齐),并且在两个子图之间没有间隙.
I basically want the right subplot to have the same height (and be aligned) with the left subplot, and have no gap between the two subplots.
我可以通过调整 figsize
达到某种程度,但这可能非常繁琐.特别是如果图形的某些其他部分发生更改,则需要多次调整 figsize
.
I can achieve this somewhat by adjusting figsize
, however that can be very tedious. Especially if some other parts of the figure is changed, necessitating tweaking the figsize
multiple times.
fig, (ax1,ax2) = plt.subplots(1,2, figsize=(8,4))
推荐答案
虽然 subplot
通常会很好地自动定位事物,但是您可以使用 axes
进行定位需要时手动.这解决了情节之间的空间问题.请参见 rect
的规范此处.
While subplot
usually does a very nice job positioning things automatically, you can use axes
to position them manually when you need to. This solves the problem of the space between your plots. See the specification of rect
here.
长宽比问题比较棘手,我敢肯定有比这更清洁的方法.您可以根据所显示图像的长宽比来指定绘图的长宽比(使用 axes
方法的 aspect
关键字).
The aspect ratio issue is trickier, and I'm sure there are approaches cleaner than this one. You can specify the aspect ratio of the plot (using the aspect
keyword of the axes
method) in terms of the aspect ratio of the image you are showing.
下面的代码段说明了 axes
的用法和 aspect
的用法.
The snippet below illustrates both the use of axes
and the use of aspect
.
import numpy as np
from matplotlib import pyplot as plt
N = 100
yRange = 1.0
x = np.arange(N)
y = np.random.random((N))*yRange
imageX = 100
imageY = 150
image = np.random.random((imageY,imageX))
imageAspect = float(imageY)/float(imageX)
myDataAspect = float(N)/yRange * imageAspect
fig = plt.figure()
ax1 = plt.axes([0.05,0.05,0.45,0.9])
ax2 = plt.axes([0.5,0.05,0.45,0.9], adjustable='box', aspect=myDataAspect)
ax2.yaxis.tick_right()
ax1.imshow(image)
ax2.plot(x,y)
fig.savefig("test.png")
plt.show()
这篇关于子图 imshow 和图共享相同的维度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!