matplotlib 标题和副标题不一致

hujrc8aj  于 2023-05-18  发布在  其他
关注(0)|答案(3)|浏览(171)

我试图同时使用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()

给出了以下未对齐的标题:

如何才能使这两个标题正确地对齐?我认为这可能是与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()

az31mfrm

az31mfrm1#

matplotlib将suptitle与 figure 对齐,将title与 subplot 对齐。您可以使用fig.subplotpars手动抖动suptitle:

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()

好好享受吧

gstyhher

gstyhher2#

我知道这不是一个完美的答案,基本上是我的评论的转发,但这里没有什么:

fig, ax = plt.subplots()

cats = ('hour', 'Two')
vals = (12, 4) 
ax.barh(cats, vals, align='center')
plt.figtext(.5,.95,'Foo Bar', fontsize=18, ha='center')
plt.figtext(.5,.9,'lol bottom text',fontsize=10,ha='center')
plt.show()

您需要根据字体大小手动调整.95和.9值。

xt0899hw

xt0899hw3#

如果你真的不需要subtitle

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')
ax.set_title('Title\nTitle')
plt.show()

相关问题