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:
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()
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()
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
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With