首页 > 解决方案 > matplotlib 中的标题和副标题对齐不一致

问题描述

我正在尝试同时使用两者ax.set_title()并将plt.suptitle()标题和副标题合并到图表中,但两者似乎并不共享相同的对齐方式。例如,以下内容:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()

cats = ('One', 'Two')
vals = (12, 4) 

ax.barh(cats, vals, align='center')
plt.suptitle('Title')
ax.set_title('Title')
plt.show()

给我们以下错位的标题:

带有短 y 标签的未对齐标题

我怎样才能让这两个标题正确对齐?我认为这可能与ax.title对齐轴和plt.suptitle对齐图形有关,但测试更长的 y 标签似乎不会影响偏移:

fig, ax = plt.subplots()

cats = ('One million tiny engines running at one hundred miles per hour', 'Two')
vals = (12, 4) 

ax.barh(cats, vals, align='center')
plt.suptitle('Title')
ax.set_title('Title')
plt.show()

带有长 y 标签的未对齐标题

标签: pythonmatplotlib

解决方案


matplotlib 将 suptitle 与figure对齐,将title与subplot对齐。您可以使用以下方法手动摇动字幕fig.subplotpars

import matplotlib.pyplot as plt

fig, ax = plt.subplots()

cats = ('One', 'Two')
vals = (12, 4) 

# Mid point of left and right x-positions
mid = (fig.subplotpars.right + fig.subplotpars.left)/2

ax.barh(cats, vals, align='center')
plt.suptitle('Title',x=mid)
ax.set_title('Title')
plt.show()

固定标题

享受!


推荐阅读