解决python绘图使用subplots出现标题重叠的问题
先上图
遇到的问题
使用plt.subplots(2,2)绘图时,子图的标题和上图重叠,影响观感:
源代码:
import numpy as npfrom scipy import signalfrom skimage import datafrom matplotlib import pyplot as plt# 定义二维灰度图像的空间滤波函数def correl2d(img, window): # 使用滤波器实现图像的空间相关 # mode = 'same'表示输出尺寸等于输入尺寸 # boundary = 'fill'表示滤波前,用常量值填充原始图像的边缘,默认常量值为0 s = 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.
参数:
部分代码:
# 显示图像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使用subplots绘图标题重叠内容请搜索 以前的文章或继续浏览下面的相关文章希望大家以后多多支持 !
最后更新于 2021-11-23 09:11:21 并被添加「」标签,已有 位童鞋阅读过。
本站使用「署名 4.0 国际」创作共享协议,可自由转载、引用,但需署名作者且注明文章出处
相关文章
- python反扒机制的5种解决方法
- 华杰胶纸座胶布机胶纸机透明胶纸座胶带锋利切割器胶带架胶条台文具胶带封口座店面工厂适用
- 如何用支付宝聊天?支付宝被网友彻底破了(图)
- 波斯猫云柔巾5包*40抽婴儿抽纸面巾保湿乳霜润柔纸巾新生宝宝专用
- Python3爬虫ChromeDriver的安装实例