【问题标题】:Inconsistent alignment of title and suptitle in matplotlibmatplotlib 中的标题和副标题对齐不一致
【发布时间】:2019-10-08 05:59:28
【问题描述】:

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

【问题讨论】:

  • 这可能是一个错误,使用两种不同的方法计算位置,始终产生轻微的偏移?否则,有这个选项:stackoverflow.com/questions/1388450/…。虽然不是很干净。
  • Suptitle 通常被想象为位于许多子图之上的标题,而不是单个子图,因此如下所述,它以图形为中心,而不是轴。如果你想要一个两行标题,你可以做ax.set_title('First Line\nSecond Line')

标签: python matplotlib


【解决方案1】:

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

享受吧!

【讨论】:

  • 谢谢,这很理想。我添加了固定图的图像,以使将来找到此答案的任何人都更清楚地进行更正。另外,欢迎来到 SO!看起来你给我开了个好头。
  • 紧的布局,你需要做两次:在tight_layout()之前——预留一些垂直空间;之后 -- 实际水平对齐它,因为 x 坐标会改变
【解决方案2】:

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

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 值。

【讨论】:

  • 这绝对是一种有趣的方式,并且对文本的其他对齐方式很有用,但我认为@soyapencil 的答案更适合我的情况。
【解决方案3】:

如果你真的不需要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()

【讨论】:

  • 我在这里给出了一个简化版本 - 在我的情况下,我确实需要suptitle
猜你喜欢
  • 1970-01-01
  • 2022-11-16
  • 2019-11-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多