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

标签 python python-2.7 matplotlib visualization

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

enter image description here

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

这是我试过的代码:

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

结果如下:

enter image description here

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

如有任何建议或更好的解决方案,我们将不胜感激!

最佳答案

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

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

enter image description here

关于python - 如何在 Matplotlib 中的图框外绘制矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41469207/

相关文章:

python - 空字符串而不是不匹配的组错误

python - 是否可以将 mmap 文件视为字节对象?

matplotlib - MNIST Matplotlib : showing color

numpy - 如何只显示meshgrid的网格

python - 尝试安装 Odoo 应用程序时出错

python - 删除 seaborn 线图图例标题

python - ATM 机编程

python - 具有单独 Python 后端的 Amazon EC2 文件结构/Web 应用程序?

python - 在 Python 中有效地在两个方向上迭代双端队列

python - mlab.griddata 错误?