Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matplotlib minus sign in tick labels has bad formatting

Matplotlib appears to use the "correct" unicode character for a minus sign in tick labels if they are set automatically. However, if I try to set them manually, it appears that it instead uses a hyphen (which looks way too small and generally bad). How can I manually change the tick labels while retaining the correct minus sign? Here is an example of a comparison between the automatic and the manual setting of the labels. Automatic:

import matplotlib.pyplot as plt
plt.plot(np.arange(-50,51,10), np.arange(0, 101, 10))
plt.xticks(np.arange(-50,51,10))

Manual:

import matplotlib.pyplot as plt
plt.plot(np.arange(-50,51,10), np.arange(0, 101, 10))
plt.xticks(np.arange(-50,51,10), np.arange(-50,51,10))

Here is the comparison of the output [1]: https://i.sstatic.net/euLmy.png

The real reason that I care about this is because I want to set the labels to values that are different from the default ones. I am running matplotlib version 3.2.2.

like image 582
leebs92 Avatar asked Feb 01 '26 10:02

leebs92


1 Answers

When using the standard tick labels, the minus signs are converted automatically to unicode minus signs. When changing the tick labels, the numbers are converted to strings. Such strings don't get the automatic replacement to unicode minus signs. A solution is to do it explicitly:

import matplotlib.pyplot as plt
import numpy as np

plt.plot(np.arange(-50, 51, 10), np.arange(11))
plt.xticks(np.arange(-50, 51, 10), [f'{x}'.replace('-', '\N{MINUS SIGN}') for x in np.arange(-50, 51, 10)])
plt.show()

comparison plot

like image 58
JohanC Avatar answered Feb 04 '26 00:02

JohanC



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!