gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 01:30:42 24 4
gpt4 key购买 nike

我在 Debian 上使用 python 2.7.13 和 matplotlib 2.0.0。我想在轴和注释上的 matplotlib 图中将小数点标记更改为逗号。但是解决方案发布了here对我不起作用。 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()

结果

enter image description here


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

关于matplotlib - 在 matplotlib 图中将小数点更改为逗号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49445935/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com