Formatting tick label for the German language, i.e., with a point as a thousands separator and comma as a decimal separator

自作多情 提交于 2020-07-22 21:20:35

问题


I want my tick labels to be formatted according to the German style, with the comma as the decimal separator and the period/point as the thousands separator. The following code works for the decimal separator on the x-axis, but does not do anything for the y-axis.


import numpy as np
import matplotlib.pyplot as plt
import locale
# Set to German locale to get comma decimal separater
locale.setlocale(locale.LC_NUMERIC, "deu_deu")
plt.ticklabel_format(useLocale=True)

# evenly sampled time at 200ms intervals
t = np.arange(0., 2., 0.2)


# red dashes, blue squares and green triangles
plt.plot(t, 1000000*t, 'r--', t, 1000000*t**2, 'bs', t, 1000000*t**3, 'g^')
plt.show()

With the above code, the y axis tick labels look as follows: 1000000, 2000000, 3000000 ...

However, I would like to look the y axis labels like this: 1.000.000 (one million), 2.000.000 (two millions), etc.


回答1:


You aren't getting the results you expect because matplotlib doesn't include the thousands separators by default. Usually, if you wanted a comma to separate thousands, you'd have to do it manually, and the same is true for decimal-marks. Below is one way to do it, adapting your code and using a lambda function.

Code:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
import locale
# Set to German locale to get comma decimal separater
locale.setlocale(locale.LC_NUMERIC, "deu_deu")

fig, ax = plt.subplots()

ax.ticklabel_format(useLocale=True)

# evenly sampled time at 200ms intervals
t = np.arange(0., 2., 0.2)

# Apply decimal-mark thousands separator formatting to y axis.
ax.get_yaxis().set_major_formatter(mpl.ticker.FuncFormatter(lambda x, loc: locale.format_string('%d', x, 1)))

# red dashes, blue squares and green triangles
ax.plot(t, 1000000*t, 'r--', t, 1000000*t**2, 'bs', t, 1000000*t**3, 'g^')
plt.show()

Output:



来源:https://stackoverflow.com/questions/60211960/formatting-tick-label-for-the-german-language-i-e-with-a-point-as-a-thousands

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!