为了重现您的问题,我使用了这段代码,它基本上显示了相同的结果:由于颜色条,右侧的图像比左侧的图像稍小。
import matplotlib.pyplot as plt
import numpy as np
D2012 = np.random.rand(10, 10)
D2013 = np.random.rand(10, 10)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize = (16,8))
P2012 = ax1.imshow(D2012,
cmap = 'magma')
P2013 = ax2.imshow(D2013,
cmap = 'magma')
ax1.set_title('2012', fontsize = 18)
ax2.set_title('2013', fontsize = 18)
ax1.axis('off')
ax2.axis('off')
plt.colorbar(P2013)
plt.show()
这给出了这个情节:
![enter image description here](https://i.stack.imgur.com/5QFLg.png)
我通过这个转变解决了:
import matplotlib.pyplot as plt
import numpy as np
D2012 = np.random.rand(10, 10)
D2013 = np.random.rand(10, 10)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize = (16,8))
ax3 = fig.add_axes([0.85, 0.1, 0.1, 0.8])
P2012 = ax1.imshow(D2012,
cmap = 'magma')
P2013 = ax2.imshow(D2013,
cmap = 'magma')
ax1.set_title('2012', fontsize = 18)
ax2.set_title('2013', fontsize = 18)
ax1.axis('off')
ax2.axis('off')
ax3.axis('off')
plt.colorbar(P2013, ax = ax3)
plt.show()
这给出了这个情节:
![enter image description here](https://i.stack.imgur.com/emssy.png)
基本上,我添加第三个轴,将其关闭并添加颜色条。您需要注意该第三轴的位置以及方法内的参数:fig.add_axes([0.85, 0.1, 0.1, 0.8])
.
我知道这当然不是最优雅的解决方案。
EDIT
一个更强大和优雅的解决方案是保留 2 个轴,但在定义它们时设置它们的大小和位置:
import matplotlib.pyplot as plt
import numpy as np
D2012 = np.random.rand(10, 10)
D2013 = np.random.rand(10, 10)
fig = plt.figure(figsize = (16,8))
ax1 = fig.add_axes([0, 0.2, 0.6, 0.6])
ax2 = fig.add_axes([0.4, 0.2, 0.6, 0.6])
P2012 = ax1.imshow(D2012,
cmap = 'magma')
P2013 = ax2.imshow(D2013,
cmap = 'magma')
ax1.set_title('2012', fontsize = 18)
ax2.set_title('2013', fontsize = 18)
ax1.axis('off')
ax2.axis('off')
plt.colorbar(P2013)
plt.show()
这给出了这个情节:
![enter image description here](https://i.stack.imgur.com/tlq5r.png)
在这种情况下,您必须注意以下几行的两个轴的位置和大小:
ax1 = fig.add_axes([0, 0.2, 0.6, 0.6])
ax2 = fig.add_axes([0.4, 0.2, 0.6, 0.6])