如何在 Matplotlib 中的图框外绘制矩形

How to draw rectangle outside of the plot frame in Matplotlib

我想生成下图样式的子图标题:

分散点顶部的标题下方应有一个灰色框。

这是我试过的代码:

x = random.sample(range(50), 50)
y= random.sample(range(50), 50)

fig = pyplot.figure()
ax = pyplot.subplot(111)
ax.scatter(x,y,label='a')
ax.set_aspect('equal')
ax.set_xlim(0,60)
ax.set_ylim(0,60)
ax.plot([0,60], [0, 60], color='k', linestyle='-', linewidth=1.25)

ax.add_patch(patches.Rectangle((0,60),60, 10,facecolor='silver',linewidth = 0))
TITLE = ax.text(26,61, r'$\mathregular{Title}$',fontsize = 14,zorder = 5,color = 'k')

结果如下:

The rectangle as the background box of title can't be shown in my result

感谢任何建议或更好的解决方案!

删除这一行:

ax.add_patch(patches.Rectangle((0,60),60, 10,facecolor='silver',linewidth = 0))

并通过添加 bbox:

更改最后一行
TITLE = ax.text(26,62, 'Title',fontsize = 14,zorder = 6, color = 'k',
                bbox={'facecolor':'silver', 'alpha':0.5, 'pad':4})

我发现给它任意长度的唯一方法是添加空格。

TITLE = ax.text(1,62, '                     Title                    ',
                fontsize = 14,zorder = 6,color = 'k', 
                bbox={'facecolor':'silver', 'alpha':0.5, 'pad':4})

有关 bbox 的更多信息,请参阅 SO 中的 this question

我认为更好的方法是对 Rectangle:

使用 clip_on=False 选项
import random
import matplotlib.pyplot as pyplot

x = random.sample(range(50), 50)
y= random.sample(range(50), 50)

fig = pyplot.figure()
ax = pyplot.subplot(111)
ax.scatter(x,y,label='a')
ax.set_aspect('equal')
ax.set_xlim(0,60)
ax.set_ylim(0,60)
ax.plot([0,60], [0, 60], color='k', linestyle='-', linewidth=1.25)

ax.add_patch(pyplot.Rectangle((0,60),60, 10,facecolor='silver',
                              clip_on=False,linewidth = 0))
TITLE = ax.text(26,61, r'$\mathregular{Title}$',fontsize = 14,zorder = 5,
                color = 'k')
pyplot.show()

这会产生一个在轴外绘制的矩形,而无需求助于额外的空格: