我有使用GridSpec
和width_ratios
和height_ratios
将代码生成在主图像图的左侧和下方具有较小图的正方形图像的代码:
import matplotlib.pyplot as plt
import numpy as np
# Some fake data.
imdata = np.random.random((100, 100))
extradata1 = np.max(imdata, axis=1)
extradata2 = np.max(imdata, axis=0)
fig = plt.figure(constrained_layout=True)
spec = fig.add_gridspec(ncols=2, nrows=2, width_ratios=(1, 8), height_ratios=(8, 1))
# Main image plot.
ax1 = fig.add_subplot(spec[:-1, 1:], aspect='equal')
ax1.imshow(imdata, cmap='viridis')
# Vertical (left) plot.
ax2 = fig.add_subplot(spec[:-1, 0], sharey=ax1)
ax2.plot(extradata1, range(imdata.shape[0]))
# Horizontal (bottom) plot.
ax3 = fig.add_subplot(spec[-1, 1:], sharex=ax1)
ax3.plot(range(imdata.shape[1]), extradata2)
plt.show()
我希望左侧图的高度和底部图的宽度分别等于主图像的高度和宽度。目前,如您所见,水平图的宽度大于图像的水平尺寸,并且它们在缩放比例时也不同。是否可以将轴尺寸限制为其他轴的尺寸?
最佳答案
用imshow()
调用aspect='auto'
应该可以解决您的问题:
ax1.imshow(imdata, cmap='viridis',aspect='auto')
有关此的更多说明,请参见此处:
Imshow: extent and aspect
import matplotlib.pyplot as plt
import numpy as np
# Some fake data.
imdata = np.random.random((100, 100))
extradata1 = np.max(imdata, axis=1)
extradata2 = np.max(imdata, axis=0)
fig = plt.figure(constrained_layout=True)
spec = fig.add_gridspec(ncols=2, nrows=2, width_ratios=(1, 8), height_ratios=(8, 1))
# Main image plot.
ax1 = fig.add_subplot(spec[:-1, 1:])
ax1.imshow(imdata, cmap='viridis',aspect='auto')
# Vertical (left) plot.
ax2 = fig.add_subplot(spec[:-1, 0], sharey=ax1)
ax2.plot(extradata1, range(imdata.shape[0]))
# Horizontal (bottom) plot.
ax3 = fig.add_subplot(spec[-1, 1:], sharex=ax1)
ax3.plot(range(imdata.shape[1]), extradata2)
结果:
关于python - 将轴尺寸限制为另一个轴的尺寸,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59212261/