如何解决Matplotlib子图中文本(标题)重叠问题?
解决Matplotlib子图文本重叠问题
1. 标题互相重叠(1行10列布局)
针对1行多列的密集子图,tight_layout()可以自动调整子图间的水平间距,避免标题互相挤压重叠。只需在所有子图绘制完成后调用该函数即可:
修改后的代码:
plt.figure(figsize=(20,4)) for plotIndex,badIndex in enumerate(misclassifiedIndexes[0:10]): plt.subplot(1,10,plotIndex+1) plt.imshow(np.reshape(X_test[badIndex],(8,8)),cmap=plt.cm.gray) plt.title("Predicted: {}, Actual: {}".format(predictions[badIndex],y_test[badIndex])) plt.tight_layout() # 添加该行自动调整间距 plt.show()
如果自动调整效果仍不理想,可手动指定水平间距:
plt.subplots_adjust(wspace=0.6) # wspace控制子图水平间距,数值按需调整
2. 标题与坐标轴重叠(2行5列布局)
这种情况是标题侵入了子图的图像/坐标轴区域,可通过以下几种方式解决:
方法一:调整标题垂直位置+tight_layout
给plt.title()添加y参数,将标题向上偏移,再配合tight_layout()优化整体布局:
plt.figure(figsize=(20,6)) # 适当增大画布高度,预留标题空间 for plotIndex,badIndex in enumerate(misclassifiedIndexes[0:10]): plt.subplot(2,5,plotIndex+1) plt.imshow(np.reshape(X_test[badIndex],(8,8)),cmap=plt.cm.gray) # y=1.05 让标题向上偏移,避免遮挡图像 plt.title("Predicted: {}, Actual: {}".format(predictions[badIndex],y_test[badIndex]), y=1.05) plt.tight_layout() plt.show()
方法二:隐藏不必要的坐标轴
如果展示的是图像,坐标轴刻度通常无意义,直接隐藏可彻底避免重叠:
plt.figure(figsize=(20,4)) for plotIndex,badIndex in enumerate(misclassifiedIndexes[0:10]): ax = plt.subplot(2,5,plotIndex+1) plt.imshow(np.reshape(X_test[badIndex],(8,8)),cmap=plt.cm.gray) plt.title("Predicted: {}, Actual: {}".format(predictions[badIndex],y_test[badIndex])) ax.axis('off') # 隐藏当前子图的坐标轴 plt.tight_layout() plt.show()
方法三:使用plt.subplots创建子图对象(推荐)
这种方式更直观,能更灵活地控制每个子图的属性:
# 直接创建2行5列的子图网格 fig, axes = plt.subplots(2,5,figsize=(20,6)) # 扁平化子图对象,方便循环遍历 for ax, badIndex in zip(axes.flat, misclassifiedIndexes[0:10]): ax.imshow(np.reshape(X_test[badIndex],(8,8)),cmap=plt.cm.gray) ax.set_title("Predicted: {}, Actual: {}".format(predictions[badIndex],y_test[badIndex]), y=1.05) ax.axis('off') # 可选隐藏坐标轴 plt.tight_layout() plt.show()
内容的提问来源于stack exchange,提问作者Amisha Dhimal
相关产品推荐
相关产品推荐

