1. 程式人生 > >python matplotlib.pyplot.subplot繪圖

python matplotlib.pyplot.subplot繪圖

轉載請註明來源https://blog.csdn.net/u010949998/article/details/80960588。

官網上使用說明:https://matplotlib.org/api/_as_gen/matplotlib.pyplot.subplot.html,上面說的很詳細,基本上都能找到需要的內容。提取幾點自己需要的內容。

使用語句

subplot(nrows, ncols, index)

  • nrows和ncols表示一張圖被分為nrows*ncols個區域
  • index表示子圖所處的位置,起始位置索引為1,即1<=index<=nrows*ncols

舉個簡單例子:

image_arr = imread('mydata/training/0/train.png') #圖片地址
plt.subplot(232)    #也可以表示為plt.subplot(2, 3, 2) 
plt.imshow(image_arr, cmap='bone')
plt.subplot(234)
plt.imshow(image_arr, cmap='bone')
plt.show()

1.迴圈過程中新增子圖

現在講圖片存在一個矩陣中,需要將其一一讀出並放入子圖中,程式碼如下:

image_arr = load_data('mydata/training', 1) #image_arr為儲存img的矩陣,image_arr[i]表示一張image矩陣;load_data為自定義函式
for i in range(25):
    plt.subplot(5, 5, 1+i)
    plt.imshow(image_arr[i], cmap='bone')
    plt.axis('off')
plt.savefig('test.tif')
plt.show()

需要注意幾個點:

  • subplot(5, 5, 1+i)不能表示成subplot(551+i),否則會出現ValueError: num must be 1 <= num <= 30, not 0。原因:當後者i=9時,此時變為subplot(560),而索引得從1開始,因此會報錯
  • plt.save()必須寫在plt.show()前面,否則儲存的圖片是空白的。
  • plt.save()可以儲存的格式有:eps, jpeg, jpg, pdf, pgf, png, ps, raw, rgba, svg, svgz, tif, tiff.

得到結果如圖

2.調整subplot子圖間距

subplots_adjust(left=None, bottom=None, right=None, top=None,
                wspace=None, hspace=None)

把None引數設定為想要調整的數值即可,但是好像只能將圖片變小,無法刪除白邊。樓主還在研究,如果有大佬知道可以在評論裡告訴我一下,謝謝