[英]Formatting tick label for the German language, i.e., with a point as a thousands separator and comma as a decimal separator
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.以下代码适用于 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()
With the above code, the y axis tick labels look as follows: 1000000, 2000000, 3000000 ...使用上面的代码,y 轴刻度标签如下所示: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.但是,我想像这样查看 y 轴标签:1.000.000(一百万)、2.000.000(两百万)等。
You aren't getting the results you expect because matplotlib doesn't include the thousands separators by default.您没有得到预期的结果,因为 matplotlib 默认不包含千位分隔符。 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.下面是一种方法,调整您的代码并使用 lambda 函数。
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:输出:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.