在 matplotlib 图中将小数点更改为逗号

change decimal point to comma in matplotlib plot

我在 Debian 上使用 python 2.7.13 和 matplotlib 2.0.0。我想在轴和注释上的 matplotlib 图中将小数点标记更改为逗号。但是 发布的解决方案对我不起作用。 locale 选项成功更改了小数点,但并未在图中暗示它。我该如何解决?我想将 locale 选项与 rcParams 设置结合使用。谢谢你的帮助。

#!/usr/bin/env python
# -*- coding: utf-8 -*- 


import numpy as np
#Locale settings
import locale
# Set to German locale to get comma decimal separater
locale.setlocale(locale.LC_NUMERIC, 'de_DE.UTF-8')
print locale.localeconv()


import numpy as np
import matplotlib.pyplot as plt
#plt.rcdefaults()

# Tell matplotlib to use the locale we set above
plt.rcParams['axes.formatter.use_locale'] = True

# make the figure and axes
fig,ax = plt.subplots(1)

# Some example data
x=np.arange(0,10,0.1)
y=np.sin(x)

# plot the data
ax.plot(x,y,'b-')
ax.plot([0,10],[0.8,0.8],'k-')
ax.text(2.3,0.85,0.8)

plt.savefig('test.png')

这是生成的输出:plot with point as decimal separator

我认为答案在于使用 Python 的格式化打印,参见 Format Specification Mini-Language。我引用:

Type: 'n'

Meaning: Number. This is the same as 'g', except that it uses the current locale setting to insert the appropriate number separator characters.

例如

import locale
locale.setlocale(locale.LC_ALL, 'de_DE')

'{0:n}'.format(1.1)

给出 '1,1'.


这可以通过 matplotlib.ticker 应用于您的示例。它允许您指定轴上刻度的打印格式。您的示例将变为:

import numpy             as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import locale

# apply German locale settings
locale.setlocale(locale.LC_ALL, 'de_DE')

# make the figure and axes
fig, ax = plt.subplots()

# some example data
x = np.arange(0,10,0.1)
y = np.sin(x)

# plot the data
ax.plot(x, y, 'b-')
ax.plot([0,10],[0.8,0.8],'k-')

# plot annotation
ax.text(2.3,0.85,'{:#.2n}'.format(0.8))

# reformat y-axis entries
ax.yaxis.set_major_formatter(ticker.StrMethodFormatter('{x:#.2n}'))

# save
plt.savefig('test.png')
plt.show()

结果是


请注意,有一点有点令人失望。显然不能使用 n 格式设置精度。见 .