[英]Reducing vertical space between subplots in matplotlib
images = wcs_request.get_data() # get image data
fig, axs = plt.subplots((len(images) + (6 - 1)) // 6, 6, figsize=(20, 20),
gridspec_kw={'hspace': 0.0, 'wspace': 0.0})
total = ((len(images) + (6 - 1)) // 6) * 6
for idx, (image, time) in enumerate(zip(images, wcs_request.get_dates())):
# Plot bbox
axs.flat[idx].imshow(image)
# Set title
axs.flat[idx].set_title(time.date().strftime("%d %B %Y"), fontsize=10, fontweight='bold')
# delete plots which have no data
for idx in range(len(images), total):
fig.delaxes(axs.flat[idx])
plt.suptitle(id, fontsize=12, fontweight='bold')
# fig.tight_layout(pad=0, h_pad=.1, w_pad=.1)
# fig.subplots_adjust(wspace=0, hspace=0)
plt.savefig(dir_out / f'{id}_map.png', dpi=300)
plt.close()
當我運行上面的代碼時,我得到一個垂直空白空間比我想要的大得多的子圖。 我該如何解決? 我已經將wspace
和hspace
設置為 0.0
好吧,有很多方法可以生成一個“漂亮”的子圖數組; 但假設您的目標是,例如創建兩行len(images)=10
的圖像:
import matplotlib.pyplot as plt
images=range(10)
## assuming you want e.g. axes on your first row:
ncols = 6
# figure out how many plots will fall into the last row using modulo
ncols_last = (len(images) % ncols)
# and (if mod > 0 !) add one to the floor operation here:
nrows = (len(images) // ncols ) + (ncols_last > 0)
fig = plt.figure()
axes={}
for i in range(len(images)):
# note that for some reason, add_subplot() counts from 1, hence we use i+1 here
axes[i] = fig.add_subplot(nrows,ncols,i+1)
# add some content
for i,ax in axes.items():
ax.text(0,0,i)
ax.set_xlim(-1,1)
ax.set_ylim(-1,1)
plt.show()
這應該在第一行給你 6 個地塊,在第二行給你 4 個地塊。 您應該能夠像這樣添加您的 plot 內容:
for idx, (image, time) in enumerate(zip(images, wcs_request.get_dates())):
# Plot bbox
axes[idx].imshow(image)
# Set title
axes[idx].set_title(time.date().strftime("%d %B %Y"), fontsize=10, fontweight='bold')
或者,使用gridspec
來訪問更多的布局選項:
import matplotlib.pyplot as plt
from matplotlib import gridspec
images=range(10)
ncols = 6
ncols_last = (len(images) % ncols)
nrows = (len(images) // ncols ) + (ncols_last > 0)
fig = plt.figure()
axes = {}
gs = gridspec.GridSpec(nrows, ncols,
left=0.1,right=.9,
bottom=0.1,top=.9,
wspace=0.25,hspace=0.3,
)
for i,(r,c) in enumerate([(r,c) for r in range(nrows) for c in range(ncols)]):
if i < len(images):
print(f"axes[{i}]: relates to the gridspec at index ({r},{c})")
axes[i] = fig.add_subplot(gs[r,c])
for i,ax in axes.items():
ax.text(0,0,i)
ax.set_xlim(-1,1)
ax.set_ylim(-1,1)
plt.show()
您可能需要查看subplots_adjust
,它可以讓您指定:
子圖之間的填充高度,作為平均軸高度的一部分。
fig, axs = plt.subplots(2,1)
fig.subplots_adjust(hspace=0.0)
所以hspace=0
根本沒有間距:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.