python绘图使用subplots出现标题重叠的解决方法
生活随笔
收集整理的這篇文章主要介紹了
python绘图使用subplots出现标题重叠的解决方法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 遇到的問題
- 解決方法
- 參考
先上圖
遇到的問題
使用plt.subplots(2,2)繪圖時,子圖的標題和上圖重疊,影響觀感:
源代碼:
import numpy as np from scipy import signal from skimage import data from matplotlib import pyplot as plt# 定義二維灰度圖像的空間濾波函數 def correl2d(img, window):# 使用濾波器實現圖像的空間相關# mode = 'same'表示輸出尺寸等于輸入尺寸# boundary = 'fill'表示濾波前,用常量值填充原始圖像的邊緣,默認常量值為0s = signal.correlate2d(img, window, mode='same', boundary='fill')return s.astype(np.uint8) # img為原始圖像 img = data.camera() # 3*3盒狀濾波模板 window_1 = np.ones((3, 3))/(3 ** 2) # 5*5盒狀濾波模板 window_2 = np.ones((5, 5))/(5 ** 2) # 9*9盒狀濾波模板 window_3 = np.ones((9, 9))/(9 ** 2) # 生成濾波結果 new_img_1 = correl2d(img, window_1) new_img_2 = correl2d(img, window_2) new_img_3 = correl2d(img, window_3) # 顯示圖像 plt.rcParams['font.sans-serif'] = ['SimHei'] # 中文 fig, axs = plt.subplots(2, 2) axs[0, 0].imshow(img, cmap='gray') axs[0, 0].set_title("攝影師原圖") axs[0, 1].imshow(new_img_1, cmap='gray') axs[0, 1].set_title("3*3盒狀濾波模板") axs[1, 0].imshow(new_img_2, cmap='gray') axs[1, 0].set_title("5*5盒狀濾波模板") axs[1, 1].imshow(new_img_3, cmap='gray') axs[1, 1].set_title("9*9盒狀濾波模板") plt.show()解決方法
方法1:在plt.show() 之前添加一句:
plt.tight_layout()函數原型:
matplotlib.pyplot.tight_layout(*, pad=1.08, h_pad=None, w_pad=None, rect=None)
作用:調整subplots子圖見的間距
Adjust the padding between and around subplots.
參數:
參考官方文檔:https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.tight_layout.html#matplotlib.pyplot.tight_layout
部分代碼:
# 顯示圖像 plt.rcParams['font.sans-serif'] = ['SimHei'] # 中文 fig, axs = plt.subplots(2, 2) axs[0, 0].imshow(img, cmap='gray') axs[0, 0].set_title("攝影師原圖") axs[0, 1].imshow(new_img_1, cmap='gray') axs[0, 1].set_title("3*3盒狀濾波模板") axs[1, 0].imshow(new_img_2, cmap='gray') axs[1, 0].set_title("5*5盒狀濾波模板") axs[1, 1].imshow(new_img_3, cmap='gray') axs[1, 1].set_title("9*9盒狀濾波模板") plt.tight_layout() plt.show()方法1測試結果:
方法2:在subplots中設置figsize
fig, axs = plt.subplots(2, 2,figsize=(6, 15)) # 顯示圖像 plt.rcParams['font.sans-serif'] = ['SimHei'] # 中文 # 設置figsize,防止圖片重疊 fig, axs = plt.subplots(2, 2,figsize=(6, 15)) axs[0, 0].imshow(img, cmap='gray') axs[0, 0].set_title("攝影師原圖") axs[0, 1].imshow(new_img_1, cmap='gray') axs[0, 1].set_title("3*3盒狀濾波模板") axs[1, 0].imshow(new_img_2, cmap='gray') axs[1, 0].set_title("5*5盒狀濾波模板") axs[1, 1].imshow(new_img_3, cmap='gray') axs[1, 1].set_title("9*9盒狀濾波模板")方法2測試結果:
參考
[1]https://blog.csdn.net/txh3093/article/details/106401484
總結
以上是生活随笔為你收集整理的python绘图使用subplots出现标题重叠的解决方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python画图fig.show()一闪
- 下一篇: python绘图subplots函数使用