基本上,当使用 matplotlib 生成绘图时,y 轴上的刻度会达到数百万。如何打开数字分组(即 1000000 显示为 1,000,000)或打开小数点分隔符?
我认为没有内置函数可以做到这一点。 (这就是我读完你的问题后的想法;我刚刚检查过,但在文档中找不到)。
无论如何,自己动手都很容易。
(下面是一个完整的示例 - 即,它将生成一个 mpl 绘图,其中一个轴具有已命名的刻度标签 - 尽管创建自定义刻度标签只需要五行代码 - 三行代码(包括 import 语句)用于函数用于创建自定义标签,两行用于创建新标签并将它们放置在指定的轴上。)
# 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()
我无法使用 doug 发布的 答案,因为由于区域设置不受支持,命令
locale.setlocale(locale.LC_ALL, 'en_US')
在我的 WSL 环境中引发了错误。
幸运的是,从 Python 3.8 开始,您可以利用 f 字符串进行变量格式化,包括数字分组。我将
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 库 matplotlib 和 numpy 才能运行此代码。