1

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 within a plot when using the matplotlib package in python, and will have to use the same units as the data being plotted.

2
  • There are options to align the text in different ways in matplotlib, see this example Commented Feb 11, 2016 at 4:15
  • This is a tricky problem, see the discussion here Commented Feb 11, 2016 at 14:56

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.