格式化德语的刻度标签,即以点作为千位分隔符,以逗号作为十进制分隔符 [英] Formatting tick label for the German language, i.e., with a point as a thousands separator and comma as a decimal separator

查看:279
本文介绍了格式化德语的刻度标签,即以点作为千位分隔符,以逗号作为十进制分隔符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

但是,我希望这样查看y轴标签:1.000.000(一百万),2.000.000(两百万),等等.

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

推荐答案

您没有得到预期的结果,因为默认情况下matplotlib不包含数千个分隔符.通常,如果要用逗号分隔成千上万,则必须手动进行,小数点也是如此.以下是一种实现方法,可修改代码并使用lambda函数.

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.

代码:

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

输出:

这篇关于格式化德语的刻度标签,即以点作为千位分隔符,以逗号作为十进制分隔符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆