[英]How to remove horizontal whitespace between matplotlib subplots with imshow
我有以下代碼,我正在嘗試刪除 3 個子圖之間的空格。 我已經嘗試了gridspec.GridSpec
和fig.subplots_adjust
,但都失敗了。
各個顏色條應該像現在一樣存在。
任何的想法?
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.axes_grid1 import make_axes_locatable
# random data
x1 = np.random.rand(1,10)
x2 = np.random.rand(1,10)
x3 = np.random.rand(1,10)
nrow, ncol = 3, 1
fig, axes = plt.subplots(nrow,ncol, figsize=(12,8))
fig.subplots_adjust(wspace=0.01, hspace=0.01)
axes = axes.flatten()
cmaps = ['Greens_r', 'Reds', 'jet']
x_all = [x1,x2,x3]
for i in range(3):
im = axes[i].imshow(x_all[i], cmap=cmaps[i])
#plt.colorbar(im, ax=axes[i])
axes[i].set_xticklabels([])
axes[i].set_yticklabels([])
axes[i].set_xticks([])
axes[i].set_yticks([])
#Make an axis for the colorbar on the right side
divider = make_axes_locatable(axes[i])
cax = divider.append_axes("right", size="5%", pad=0.05)
fig.colorbar(im, cax=cax)
您可以先按原樣繪制圖形,然后通過將它們移動它們之間的間隙減去一定space
來調整頂部和底部軸相對於中間軸的 position。 如果您按照 Jody 的建議使用inset_axes
,這是最簡單的。
import matplotlib.pyplot as plt
import matplotlib.transforms as mt
import numpy as np
# random data
np.random.seed(42)
x_all = (np.random.rand(1,10), np.random.rand(1,10), np.random.rand(1,10))
cmaps = ['Greens_r', 'Reds', 'jet']
space = 0.01
fig, axes = plt.subplots(3, 1, figsize=(12,6))
for ax, x, cmap in zip(axes, x_all, cmaps):
ax.axis('off')
im = ax.imshow(x, cmap=cmap)
cax = ax.inset_axes([1 + space, 0, 0.05, 1])
fig.colorbar(im, ax=ax, cax=cax)
fig.canvas.draw()
t = mt.Affine2D().translate(0, axes[1].get_position().y1 - axes[0].get_position().y0 + space)
axes[0].set_position(mt.TransformedBbox(axes[0].get_position(), t))
t = mt.Affine2D().translate(0, axes[1].get_position().y0 - axes[2].get_position().y1 - space)
axes[2].set_position(mt.TransformedBbox(axes[2].get_position(), t))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.