格式化德语的刻度标签,即以点作为千位分隔符,以逗号作为小数点分隔符

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

我希望我的刻度标签按照德国风格进行格式化,逗号作为小数点分隔符,period/point 作为千位分隔符。以下代码适用于 x 轴上的小数点分隔符,但对 y 轴没有任何作用。


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()

使用上述代码,y 轴刻度标签如下所示:1000000、2000000、3000000 ...

但是,我想像这样查看 y 轴标签:1.000.000(一百万)、2.000.000(两百万)等

您没有得到预期的结果,因为默认情况下 matplotlib 不包含千位分隔符。通常,如果你想用逗号分隔千位,你必须手动完成,小数点也是如此。下面是一种方法,调整您的代码并使用 lambda 函数。

代码:

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()

输出: