2

I am struggling to make the text in matplotlib to have the same visual length after filling space. It always doesn't work for me.

Here is what I have tried,

from matplotlib import pyplot as plt

fig = plt.figure()
plt.text(0,1,'how are you', bbox=dict(facecolor='red', alpha=0.5))
plt.text(0,0,'how'.ljust(len('how are you'), bbox=dict(facecolor='red', alpha=0.5))
plt.show()

And ideas?

Thanks!

Kungfu_panda
  • 411
  • 4
  • 7

1 Answers1

4

ljust appends as many spaces to the text as you specify. However with normal fonts a space is smaller than most other letters. Compare:

enter image description here

The lower text is a written in a so called monospace font, where each letter (including space) has the same space - hence the name.

You would need to use such a font to make your program work in the intended way:

from matplotlib import pyplot as plt
plt.rcParams['font.family'] = 'monospace'

fig = plt.figure()
plt.text(0,1,'how are you', bbox=dict(facecolor='red', alpha=0.5))
plt.text(0,0,'how'.ljust(len('how are you')), bbox=dict(facecolor='red', alpha=0.5))
plt.show()

enter image description here

If this is not an option, you may place a rectangle behind the text of which you set the width to your desire, see this question Matplotlib: how to specify width of x-label bounding box

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712