简体   繁体   中英

How to put text inside a box on a plot in matplotlib

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

Here is the code from the example :

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

Matplotlib coordinates

Using transform=ax.transAxes we can put elements inside a plot in using coordinate system in which point (0, 0) is lower left corner, (0, 1) upper left, (1, 1) upper right, and so on.

To be specific: if we put a text box using position (0, 0) a specific point called anchor will be placed in lower left corner. To change anchor you need to add two arguments to the function call: verticalalignment (possible values: center , top , bottom , baseline ) and horizontalalignment (possible values: center , right , left ).

So to put box in lower left corner, you need to put lower left corner of the box in the lower left corner of the figure:

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

Anyways here is the link to ipython-notebook with example for all placements .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM