0

Using matplotlib I want to draw several shapes (e.g., rectangles) that get a describing text attached which starts at the upper left corner of the shape. Sometimes, the text is to long so that it overlaps with the text of the next shape. overlapping text

MWE given below:

import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
fig, ax = plt.subplots()

ax.add_patch(Rectangle((0,0), 4, 5))
ax.add_patch(Rectangle((5,0), 4, 5))

plt.text(0, 5.5, 'very very very very long text')
plt.text(5, 5.5, 'another text')

plt.xlim([-1, 11])
plt.ylim([-1, 7])
plt.show()

How can I get the point at which the first text ends so that I can adjust the start of the next shape?

I found that the Text object has a get_window_extent() function, but this works just after plt.show() if no renderer is specified and also returns not the (x,y) coordinates but instead the pixels I think.

Thanks for your answers!

akra1
  • 144
  • 1
  • 1
  • 12
  • see https://stackoverflow.com/questions/69473844/can-you-calculate-the-size-of-a-text-annotation-in-matplotlib (and many others) – JohanC Jan 19 '23 at 08:04

0 Answers0