Matplotlib 数字分组(小数分隔符)

3 投票
2 回答
1500 浏览
提问于 2025-04-15 21:08

简单来说,当你用matplotlib生成图表时,y轴的数值会变得很大,甚至达到百万级别。你想知道怎么才能让这些数字分组显示,比如把1000000显示成1,000,000,或者怎么开启小数点分隔符。

2 个回答

0

我无法使用doug发布的答案,因为在我的WSL环境中,命令locale.setlocale(locale.LC_ALL, 'en_US')出现了错误,原因是这个地区设置不被支持。

幸运的是,从Python 3.8开始,你可以使用f-strings来格式化变量,包括数字分组。我定义了一个叫fnx的lambda函数,内容是fnx = lambda x : f'{x:,}',这样代码就能按预期工作了。

下面是完整的可运行代码,已经修改过了。

fnx = lambda x : f'{x:,}'

from matplotlib import pyplot as plt
import numpy as np

data = np.random.randint(15000, 85000, 50).reshape(25, 2)
x, y = data[:, 0], data[:, 1]

fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.plot(x, y, "ro")
default_xtick = range(20000, 100000, 10000)

# The crucial part:
# Create custom tick labels
new_xtick = map(fnx, default_xtick)
# Set these labels on the axis
ax1.set_xticklabels(new_xtick)

plt.show()

请注意,运行这段代码需要安装Python库matplotlibnumpy

3

我觉得没有现成的函数可以做到这一点。(这是我在读了你的问题后想到的;我刚查了一下文档,也没找到相关的函数)。

不过,自己写一个其实很简单。

(下面是一个完整的例子——也就是说,它会生成一个mpl图,其中一个坐标轴的刻度标签是带逗号的——虽然你只需要五行代码就能创建自定义的刻度标签——其中三行(包括导入语句)是用来创建自定义标签的函数,另外两行是用来生成新标签并把它们放到指定的坐标轴上。)

# first code a function to generate the axis labels you want 
# ie, turn numbers greater than 1000 into commified strings (12549 => 12,549)

import locale
locale.setlocale(locale.LC_ALL, 'en_US')
fnx = lambda x : locale.format("%d", x, grouping=True)

from matplotlib import pyplot as PLT
import numpy as NP

data = NP.random.randint(15000, 85000, 50).reshape(25, 2)
x, y = data[:,0], data[:,1]

fig = PLT.figure()
ax1 = fig.add_subplot(111)
ax1.plot(x, y, "ro")
default_xtick = range(20000, 100000, 10000)

# these two lines are the crux:
# create the custom tick labels
new_xtick = map(fnx, default_xtick)
# set those labels on the axis
ax1.set_xticklabels(new_xtick)

PLT.show()

撰写回答