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

24
我该如何停止在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()

1
你可能想在Matplotlib的用户邮件列表上提出这样具体的问题。 - Thomas K
3
用户邮件列表是什么? - user809167
我感到困惑,因为我不确定“对数符号标签”是什么意思。您是想更改标签的格式(从10^3更改为1000),还是想在a中的位置添加刻度线(或用刻度线替换当前的刻度线)? - DSM
将标签的格式更改为1000(从10 ^ 3)。 - user809167
10^3不是对数表示法,而是科学计数法。 - NeutronStar
2个回答

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)))))

应该可以工作。如果刻度标签的位置最终处于4.99之类的地方,'%d'将会出现问题,但你会明白的。

请注意,根据轴的限制,您可能需要对较小的格式化程序set_minor_formatter执行相同的操作。


+1 还提供了一个基于 lambda 的示例。这几乎为每个可能的值到字符串映射打开了大门。在我看来,这个答案应该被接受。 - bluenote10

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()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接