Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center a label inside a circle with matplotlib

I would like to plot circles with matplotlib (patches), and annotate them. The annotation would be a word, and it needs to be in the centre of the circle.

So far, I can plot a circle and annotate it: enter image description here

But the annotation is not centred, neither horizontally or vertically. In order to do that, I would need access to the dimensions of the text.

Is there a way to access the dimensions of the text in "the coordinate systems" ?. For example, if the circle has a radius of 15 (15 something, not pixels), the text would have a length of 12 something (not pixels).

I'm open to any other suggestion on how to do that.

Here is my code so far:

import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.figure import Figure

fig, ax = plt.subplots()

ax = fig.add_subplot(111)

x = 0
y = 0

circle = plt.Circle((x, y), radius=1)

ax.add_patch(circle)

label = ax.annotate("cpicpi", xy=(x, y), fontsize=30)

ax.axis('off')
ax.set_aspect('equal')
ax.autoscale_view()

plt.show()
like image 242
JPFrancoia Avatar asked May 04 '18 10:05

JPFrancoia


2 Answers

You need to set the horizontal alignment in ax.annotate using ha="center". The same thing can be done for the vertical direction if necessary using the argument va="center"

fig, ax = plt.subplots()

ax = fig.add_subplot(111)

x = 0
y = 0

circle = plt.Circle((x, y), radius=1)

ax.add_patch(circle)

label = ax.annotate("cpicpi", xy=(x, y), fontsize=30, ha="center")

ax.axis('off')
ax.set_aspect('equal')
ax.autoscale_view()

plt.show()

enter image description here

like image 55
DavidG Avatar answered Nov 07 '22 19:11

DavidG


You can add two additional arguments to the annotate() call:

label = ax.annotate(
    "cpicpi",
    xy=(x, y),
    fontsize=30,
    verticalalignment="center",
    horizontalalignment="center"
)

(See the docs for the arguments of annotate and of Text – whose constructor is called by annotate)

like image 34
Nicola Sap Avatar answered Nov 07 '22 17:11

Nicola Sap