Matplotlib - 对数刻度,但需要非对数标签

24 投票
2 回答
15415 浏览
提问于 2025-04-16 20:02

我该如何让y轴不显示对数形式的标签呢?

我对对数刻度没意见,但我想在Y轴上显示实际的数值,比如说[500, 1500, 4500, 11000, 110000]。我不想一个个手动标记每个刻度,因为这些标签将来可能会变化(我试过不同的格式化方法,但都没成功)。下面是示例代码。

谢谢,

-collern2

import matplotlib.pyplot as plt
import numpy as np

a = np.array([500, 1500, 4500, 11000, 110000])
b = np.array([10, 20, 30, 40, 50])

fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.set_yscale('log')

plt.plot(b, a)
plt.grid(True)
plt.show()

2 个回答

3

使用 ticker.FormatStrFormatter

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

a = np.array([500, 1500, 4500, 11000, 110000])
b = np.array([10, 20, 30, 40, 50])

fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.set_yscale('symlog')

ax.yaxis.set_major_formatter(ticker.FormatStrFormatter("%d"))

plt.plot(b, a)
plt.grid(True)

plt.show()
33

如果我理解得没错,

ax.set_yscale('log')

任何一个

ax.yaxis.set_major_formatter(matplotlib.ticker.ScalarFormatter())
ax.yaxis.set_major_formatter(matplotlib.ticker.FormatStrFormatter('%d'))
ax.yaxis.set_major_formatter(matplotlib.ticker.FuncFormatter(lambda x, pos: str(int(round(x)))))

都应该可以用。'%d' 这个格式在刻度标签的位置如果是像 4.99 这样的地方可能会有问题,但你大概明白我的意思。

注意,你可能还需要对次要刻度的格式化器 set_minor_formatter 进行同样的处理,这取决于坐标轴的范围。

撰写回答