我正在尝试并排绘制同一图像的两个版本。当我绘制其中一张图像没有颜色条的图形时,它似乎具有正确的尺寸:
但是当我向左侧图像添加颜色条时,它会以某种方式缩小图像:
这是我注释掉颜色栏行的代码:
def plot_amaps(self, anisotropy_map, parallel):
timepoint = self.t * self.timestep
amap_directory = self.directory + "amaps/"
fig = plt.figure(facecolor='w', dpi=180)
ax1 = fig.add_subplot(121)
fig.subplots_adjust(top=0.85)
ax1.grid(False)
txt = "Mean(r) = %.3f SD(r)= %.3f t=%dmin"
txt = txt %(self.mean, self.sd, timepoint)
ax1.set_title(txt)
amap = ax1.imshow(anisotropy_map, cmap="jet", clim = self.clim)
#divider = make_axes_locatable(ax1)
#cax = divider.append_axes('right', size='5%', pad=0.05)
#fig.colorbar(amap, cax=cax)
ax2 = fig.add_subplot(122)
ax2.set_title("Intensity image", fontsize=10)
ax2.imshow(parallel, cmap="gray")
ax2.grid(False)
ax1.axis('off')
ax2.axis('off')
if self.save is True:
self.make_plot_dir(amap_directory)
name = self.cell + "_time_"+str(timepoint)
plt.savefig(amap_directory+name+self.saveformat, bbox_inches='tight')
else:
plt.show()
plt.close('all')
我做错了什么,如何确保两个图像的大小相同?
使用时
divider = make_axes_locatable(ax1)
cax = divider.append_axes('right', size='5%', pad=0.05)
您明确要求轴小 5%。因此,如果您不希望这样,则不应使用
make_axes_locatable
创建颜色条的轴。
相反,您可以使用
在图形上的任意点简单地创建轴cax = fig.add_axes([left, bottom, width, height])
其中
left, bottom, width, height
的数字单位范围为0到1。然后为其添加颜色条。plt.subplots_adjust(wspace=0.3)
当然,您必须对这些数字进行一些实验。
当您使用
append_axes()
时,它实际上会减小 ax1
的大小,为颜色图腾出空间。
如果您想确保轴的大小不改变,您应该显式创建它们。
这是我的尝试:
import matplotlib.gridspec as gridspec
gs = gridspec.GridSpec(1,3,width_ratios=[5,1,5])
fig = plt.figure(facecolor='w', dpi=180)
randomData = np.random.random(size=(100,100))
ax1 = fig.add_subplot(gs[0])
ax1.grid(False)
txt = "Mean(r) = %.3f SD(r)= %.3f t=%dmin"
txt = txt %(0, 0, 0)
ax1.set_title(txt)
amap = ax1.imshow(randomData, cmap="jet")
#divider = make_axes_locatable(ax1)
#cax = divider.append_axes('right', size='5%', pad=0.05)
fig.colorbar(amap, cax=fig.add_subplot(gs[1]))
ax2 = fig.add_subplot(gs[2])
ax2.set_title("Intensity image", fontsize=10)
ax2.imshow(randomData, cmap="gray")
ax2.grid(False)
ax1.axis('off')
ax2.axis('off')
作为已接受解决方案的替代方案,您还可以在第二个子图上制作另一个相同大小的轴并关闭轴,这样它就不会出现,但以相同的方式缩小图像:
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import numpy as np
# Create a random image to plot
img = np.random.random((25, 25))
threshold = 0.8
# Create a plot with two subplots
fig, axes = plt.subplots(1, 2, tight_layout=True)
ax = axes.ravel()
# Subplot 0
pos = ax[0].imshow(img)
ax[0].set_title('Random')
# Create the colorbar axis on the right side of ax[0]
div0 = make_axes_locatable(ax[0])
cax0 = div0.append_axes("right", size="5%", pad=0.1)
fig.colorbar(pos, cax=cax0)
# Subplot 1
ax[1].imshow(img > threshold)
ax[1].set_title(f'Random > {threshold}')
# Create a mock-colorbar axis on ax[1] to take up the same space
div1 = make_axes_locatable(ax[1])
cax1 = div1.append_axes("right", size="5%", pad=0.1)
# Turn off the axis so you can't see it
cax1.set_axis_off()