Skip to content Skip to sidebar Skip to footer

Matplotlib Calculate Axis Coordinate Extents Given String

I am trying to center an axis text object by: Getting the width in coordinates of the text divided by 2. Subtracting that value from the center (provided) location on the x-axis.

Solution 1:

You can create a text object, obtain its bounding box and then remove the text again. You may transform the bounding box into data coordinates (I assume that you mean data coordinates, not axes coordinates in the question) and use those to create a left aligned text.

import matplotlib.pyplot as plt

ax = plt.gca()
ax.set_xlim(0,900)
#create centered text 
text = ax.text(400,0.5, "string", ha="center", color="blue")
plt.gcf().canvas.draw()
bb = text.get_window_extent()
# remove centered text
text.remove()
del text
# create left aligned text from position of centered text
bb2 = bb.transformed(ax.transData.inverted())
text = ax.text(bb2.x0,0.5, "string", ha="left", color="red")

plt.show()

Post a Comment for "Matplotlib Calculate Axis Coordinate Extents Given String"