如何将文本放在matplotlib中的绘图框内

jb.*_*jb. 6 python matplotlib

我想在matplotlib图上的一个方框中放一个文本,但是文档只提供了如何将它放在右上角的示例(并且选择不同的角落并不是很简单).

jb.*_*jb. 6

以下是示例中的代码:

# these are matplotlib.patch.Patch properties
props = dict(boxstyle='round', facecolor='wheat', alpha=0.5)

# place a text box in upper left in axes coords
ax.text(0.05, 0.95, textstr, transform=ax.transAxes, fontsize=14,
    verticalalignment='top', bbox=props)
Run Code Online (Sandbox Code Playgroud)

Matplotlib坐标

使用transform=ax.transAxes我们可以使用坐标系将元素放入图中,其中点(0,0)是左下角,(0,1)左上角,(1,1)是右上角,依此类推.

具体来说:如果我们使用位置(0,0)放置一个文本框,则调用的特定点将anchor放在左下角.要改变锚,你需要两个参数添加到函数调用: verticalalignment(可能值: center,top,bottom,baseline)和horizontalalignment(可能的值:center,right,left).

因此,要将框放在左下角,您需要将框的左下角放在图的左下角:

# place a text box in lower left in axes coords
ax.text(0.05, 0.05, textstr, transform=ax.transAxes, fontsize=14,
    verticalalignment='bottom', bbox=props)
Run Code Online (Sandbox Code Playgroud)

无论如何,这里是ipython-notebook的链接,其中包含所有展示位置的示例.

  • 您还可以使用“annotate”,这使得这一切变得更容易。 (2认同)