Matplotlib:轴的逗号分隔数字格式

Pat*_*k A 14 python matplotlib

我试图将我的轴的格式更改为在Python 2.7下运行的Matplotlib中以逗号分隔,但我无法这样做.

我怀疑我需要使用FuncFormatter,但我有点不知所措.

有人可以帮忙吗?

Tho*_*anz 14

我知道问题已经过时了,但是由于我目前正在寻找类似的解决方案,所以如果其他人需要,我决定留下评论以供将来参考.

对于替代解决方案,请使用该locale模块并激活matplotlib中的区域设置格式.

例如,在欧洲的主要地区,逗号是所需的分隔符.您可以使用

#Locale settings
import locale
locale.setlocale(locale.LC_ALL, "deu_deu")
import matplotlib as mpl
mpl.rcParams['axes.formatter.use_locale'] = True

#Generate sample plot
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0,10,501)
y = np.sin(x)
ax = plt.subplot(111)
ax.plot(x,y)
ax.yaxis.set_major_formatter(y_format)  # set formatter to needed axis

plt.show()
Run Code Online (Sandbox Code Playgroud)

产生与Andrey的解决方案相同的情节,但你可以确定它在角落情况下也能正常运行.

  • 谢谢.我认为这应该是首选方式.请注意,对于Linux,语言环境字符串可能不同(在我的例子中为"de_DE.utf8").在控制台中检查`locale -a`输出是否有可能的值.也没有必要设置格式化程序(C&P错误) (2认同)

And*_*lev 12

是的,你可以matplotlib.ticker.FuncFormatter用来做这件事.

这是一个例子:

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

def func(x, pos):  # formatter function takes tick label and tick position
    s = str(x)
    ind = s.index('.')
    return s[:ind] + ',' + s[ind+1:]   # change dot to comma

y_format = tkr.FuncFormatter(func)  # make formatter

x = np.linspace(0,10,501)
y = np.sin(x)
ax = plt.subplot(111)
ax.plot(x,y)
ax.yaxis.set_major_formatter(y_format)  # set formatter to needed axis

plt.show()
Run Code Online (Sandbox Code Playgroud)

这导致以下情节:

funcformatter plot

  • 在Python 2.7中,您可以简单地使用字符串格式函数的内置逗号分隔功能,而不是定义上面的`func`,如下所示:`FuncFormatter('{:,.0f}'.format)` (6认同)
  • 您可以简单地编写`ax.get_yaxis().set_major_formatter(ticker.FuncFormatter(lambda x,pos:str(x).replace('.',','),而不是定义一个特殊函数`func(x,pos)`. )))` (3认同)
  • @Karlo我想最简单的解决方案是将`lambda`函数修改为`lambda x,pos:'{:.2f}'.format(x).replace('.',',')` (2认同)

pyt*_*ist 5

我认为问题实际上是指在y轴上表示300000为300,000.

从安德烈的答案中借鉴,稍作调整,

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

def func(x, pos):  # formatter function takes tick label and tick position
   s = '{:0,d}'.format(int(x))
   return s


y_format = tkr.FuncFormatter(func)  # make formatter

x = np.linspace(0,10,501)
y = np.sin(x)
ax = plt.subplot(111)
ax.plot(x,y)
Run Code Online (Sandbox Code Playgroud)

ax.yaxis.set_major_formatter(y_format)#set formatter to need axis

plt.show()