Skip to content Skip to sidebar Skip to footer

How To Calculate The Dimensions Of A Text Object In Python's Matplotlib

I'm trying to calculate the dimensions of a text object, given the characters in the array, point size and font. This is to place the text string in such a way that it's centered w

Solution 1:

As pointed out in the comments, matplotlib allows for centering text (and other alignments). See documentation here.

If you really need the dimensions of a text object, here is a quick solution that relies on drawing the text once, getting its dimensions, converting them to data dimensions, deleting the original text, then re-plotting the text centered in data coordinates. This question provides a useful explanation.

import matplotlib.pyplot as plt
plt.ion()

fig = plt.figure()
ax = fig.add_subplot(111)

xlim = ax.get_xlim()
ylim = ax.get_ylim()

textToPlot = 'Example'

t = ax.text(.5*(xlim[0] + xlim[1]), .5*(ylim[0] + ylim[1]), textToPlot)

transf = ax.transData.inverted()
bb = t.get_window_extent(renderer = fig.canvas.renderer)
bb_datacoords = bb.transformed(transf)

newX = .5*(xlim[1] - xlim[0] - (bb_datacoords.x1 - bb_datacoords.x0))
newY = .5*(ylim[1] - ylim[0] - (bb_datacoords.y1 - bb_datacoords.y0))

t.remove()
ax.text(newX, newY, textToPlot)

ax.set_xlim(xlim)
ax.set_ylim(ylim)

The result of this script looks like this: enter image description here

Post a Comment for "How To Calculate The Dimensions Of A Text Object In Python's Matplotlib"