Matplotlib:如何统一所有子图名称的显示位置?
统一多子图标题位置的解决方案
可以通过遍历所有子图,手动指定标题的位置参数,强制让所有子图标题显示在同一侧(左侧或右侧)。以下是修改后的代码及说明:
修改后的完整代码
def Grahp2(): import pandas as pd import matplotlib.pyplot as plt from matplotlib.widgets import MultiCursor df = pd.read_csv('Dataset.csv') names = ['P', 'Filter', 'Answers', 'step','step2','Comulative', 'Delta_ema','ComulativePOC', 'Delta_P', 'Sum','SpeedUp', 'M' ] features = df[names] features.index = df['Time'] axs = features.plot(subplots=True) # 遍历子图,统一设置标题位置为左侧(可改为right设为右侧) for ax, title_name in zip(axs, names): ax.set_title(title_name, loc='left') # 移除默认ylabel避免和标题重叠 ax.set_ylabel('') cursor = MultiCursor(axs[1].get_figure().canvas, axs) # 调整左侧边距,给标题预留显示空间 plt.subplots_adjust(wspace=0.19, hspace=0.05, top=0.99, right=0.988, bottom=0.052, left=0.12) plt.show()
核心修改说明
- 强制统一标题位置:通过
ax.set_title()的loc参数(可选left/right),手动指定每个子图标题的显示位置,覆盖pandas默认的自动对齐逻辑。 - 优化布局:移除子图默认的y轴标签(
ax.set_ylabel('')),避免和左侧标题重叠;同时调整subplots_adjust的left参数(若设右侧标题则调整right),确保标题完全显示。
如果需要将所有标题放在右侧,只需把loc='left'替换为loc='right',并将subplots_adjust的right参数适当调小(比如改为0.88)即可。
内容的提问来源于stack exchange,提问作者Genry
相关产品推荐
相关产品推荐

