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

将matplotlib绘图中的小数点更改为逗号,matplotlib,formatting,decimal,locale,marker,Matplotlib,Formatting,Decimal,Locale,Marker,我在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 setting

我在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')

以下是生成的输出:

我认为答案在于使用Python的格式化打印,请参阅。我引述:

类型:
'n'

意思:数字。这与
'g'
相同,只是它使用当前区域设置插入适当的数字分隔符

比如说

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

'{0:n}'.format(1.1)
给出
'1,1'


这可以应用到您的示例中。它允许您为沿轴的刻度指定打印格式。然后,您的示例变成:

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
格式设置精度。请参阅。

谢谢您的努力。但是这个方法在我的系统中引发了一个ValueError,它说:ValueError:
浮动格式说明符中不允许使用替代形式(#),这可能是Python 2.7和Python 3.6之间的差异,然后。。。您可以尝试简单地删除
#
,但这可能仍然不是您想要的。谢谢。删除
#
对我来说很好。我不需要进一步定义精度。在任何情况下,您都可以手动指定所有字符串和
name.replace(“.”、“,”)
,但我可以想象这不是您想要的。