Kungfu_panda
Kungfu_panda

Reputation: 421

matplotlib how to make text to have the same length visually after filling space

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!

Upvotes: 3

Views: 2421

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339102

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

Upvotes: 5

Related Questions