Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'half space' in matplotlib labels and legend

How can I insert a half space in the text of matplotlib labels or legends, e.g. between numbers and their units? A simple workaround would be to use latex rendering, but is there an other way, e.g. using unicode characters?

like image 341
a.smiet Avatar asked May 23 '26 21:05

a.smiet


2 Answers

You don't need to use latex rendering. Normal MathText is sufficient. It still has most basic latex capabities, e.g. a small space as \, available.

import matplotlib.pyplot as plt

plt.plot([1,2], label='$100\,$s')
plt.plot([1,3], label='$100$ s')

plt.legend()

plt.show()

enter image description here

like image 50
ImportanceOfBeingErnest Avatar answered May 26 '26 10:05

ImportanceOfBeingErnest


You can use the unicode thin space character u"\u2009".

For example, compare the width of the spaces in the legend text here between the "10" and the "km":

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(1)

ax.plot(np.arange(5), 'r-', label='10 km (normal space)')
ax.plot(5.-np.arange(5), 'b-', label=u"10\u2009km (thin space)")

ax.legend()

plt.show()

enter image description here

like image 32
tmdavison Avatar answered May 26 '26 10:05

tmdavison



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!