[英]How to make the size of subplot equally?
我正在使用 matplotlib 和 GridSpec 在 3x3 子圖中繪制 9 個圖像。
fig = plt.figure(figsize=(30,40))
fig.patch.set_facecolor('white')
gs1 = gridspec.GridSpec(3,3)
gs1.update(wspace=0.05, hspace=0.05)
ax1 = plt.subplot(gs1[0])
ax2 = plt.subplot(gs1[1])
ax3 = plt.subplot(gs1[2])
ax4 = plt.subplot(gs1[3])
ax5 = plt.subplot(gs1[4])
ax6 = plt.subplot(gs1[5])
ax7 = plt.subplot(gs1[6])
ax8 = plt.subplot(gs1[7])
ax9 = plt.subplot(gs1[8])
ax1.imshow(img1,cmap='gray')
ax2.imshow(img2,cmap='gray')
...
ax9.imshow(img9,cmap='gray')
但是,每行的圖像大小不同。 例如,第一行圖片大小為256x256,第二行圖片大小為200x200,第三行圖片大小為128x128
我想在子圖中繪制相同大小的圖像。 我應該如何在python中使用它? 謝謝
不要使用matplotlib.gridspec
,而是使用figure.add_subplot
如下面的可運行代碼所示。 但是,在進行一些繪圖時,您需要set_autoscale_on(False)
以抑制其大小調整行為。
import numpy as np
import matplotlib.pyplot as plt
# a function that creates image array for `imshow()`
def make_img(h):
return np.random.randint(16, size=(h,h))
fig = plt.figure(figsize=(8, 12))
columns = 3
rows = 4
axs = []
for i in range(columns*rows):
axs.append( fig.add_subplot(rows, columns, i+1) )
# axs[-1] is the new axes, write its title as `axs[number]`
axs[-1].set_title("axs[%d]" % (i))
# plot raster image on this axes
plt.imshow(make_img(i+1), cmap='viridis', alpha=(i+1.)/(rows*columns))
# maniputate axs[-1] here, plot something on it
axs[-1].set_autoscale_on(False) # suppress auto sizing
axs[-1].plot(np.random.randint(2*(i+1), size=(i+1)), color="red", linewidth=2.5)
fig.subplots_adjust(wspace=0.3, hspace=0.4)
plt.show()
結果圖:
我想你想以不同的尺寸顯示圖像,這樣不同圖像的所有像素的大小都相同。
這通常很難,但是對於子圖網格的行(或列)中的所有圖像大小相同的情況,它變得容易。 這個想法可以是使用 gridspec 的height_ratios
(或width_ratios
在列的情況下)參數並將其設置為圖像的像素高度(寬度)。
import matplotlib.pyplot as plt
import numpy as np
images = [np.random.rand(r,r) for r in [25,20,12] for _ in range(3)]
r = [im.shape[0] for im in images[::3]]
fig, axes = plt.subplots(3,3, gridspec_kw=dict(height_ratios=r, hspace=0.3))
for ax, im in zip(axes.flat, images):
ax.imshow(im)
plt.show()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.