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

Han*_*gzu 3 python visualization matplotlib python-2.7

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

在此处输入图片说明

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

这是我尝试过的代码:

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')
Run Code Online (Sandbox Code Playgroud)

结果显示如下:

在此处输入图片说明

矩形作为标题的背景框无法显示在我的结果中

任何建议或更好的解决方案表示赞赏!

hei*_*Bug 5

我认为更好的方法是对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()
Run Code Online (Sandbox Code Playgroud)

这将产生一个在轴外绘制的矩形,而无需诉诸额外的空间:

在此处输入图片说明