[英]How to force same size between matplotlib subplot image axes
Suppose I have the following code to create three side-by-side images: 假设我有以下代码来创建三个并排图像:
n=10
x = np.random.rand(n,1)
y = np.random.rand(1,n)
z = np.random.rand(n,n)
fig, ax = plt.subplots(1, 3)
ax[0].imshow(x)
ax[1].imshow(z)
ax[2].imshow(y)
However, the axes autoscale so that the vertical axis in the first image is larger than the vertical axis in the second. 但是,轴是自动缩放的,因此第一个图像中的垂直轴大于第二个中的垂直轴。
Is there a way to programmatically force all image dimensions of size n
to look the same in the three plots, regardless of window size? 有没有办法以编程方式强制大小为
n
所有图像尺寸在三个图中看起来相同,而不管窗口大小? I'm looking for a way to either link the axes or the images so that the vertical axis of the first plot is the same size as the vertical axis of the second plot, and the horizontal axis of the third plot is the same size as the horizontal axis of the second plot, regardless of window size. 我正在寻找一种方法来链接轴或图像,以便第一个图的垂直轴与第二个图的垂直轴大小相同,第三个图的水平轴与第二个图的水平轴,与窗口大小无关。 ie something like this:
即是这样的:
I think one easiest way is to use aspect='auto'
with ax[1].imshow(z)
. 我认为最简单的方法是使用
aspect='auto'
ax[1].imshow(z)
aspect='auto'
ax[1].imshow(z)
aspect='auto'
使用ax[1].imshow(z)
。 But this will distort the image in a way that may be not the same as what you've shown in the question. 但这会使图像扭曲,可能与您在问题中显示的方式不同。 And it may not work for cases where there is no single
n
. 并且它可能不适用于没有单个
n
。 I'm not sure if I got you 100%, but let me try this method. 我不确定我是否100%给你,但让我尝试这种方法。 The key idea here are:
这里的关键想法是:
fig
. fig
的纵横比。 The exact ratio comes from both your image data and your subplot layout. Here is my example code and figure: 这是我的示例代码和图:
import matplotlib.pyplot as plt
from matplotlib.figure import figaspect
import numpy as np
n = 10
x = np.random.rand(n,1)
y = np.random.rand(1,n)
z = np.random.rand(n,n)
width_max = max(s.shape[0] for s in [x, y, z])
height_max = max(s.shape[1] for s in [x, y, z])
row = 1
col = 3
fig, ax = plt.subplots(row, col)
w, h = figaspect(row*width_max/(col*height_max))
fig.set_size_inches(w, h)
ax[0].imshow(x)
ax[1].imshow(z)
ax[2].imshow(y)
plt.tight_layout()
plt.show()
I hope this solves your real problem. 我希望这能解决你真正的问题。 I think this also works for a case like:
我认为这也适用于以下情况:
x = np.random.rand(3,1)
y = np.random.rand(1,10)
z = np.random.rand(7,6)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.