在matplotlib中具有零值的Logscale图

时间:2013-06-03 19:52:27

标签: python matplotlib

我目前正在使用logscale,以便更有可能绘制我的数据。不过,我的数据也包含零值。我知道这些零值在logscale上不起作用,因为没有定义log(0)。

所以,例如,

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot([0,1,2],[10,10,100],marker='o',linestyle='-')
ax.set_yscale('log')
ax.set_xscale('log')

完全省略零值。这种行为可以接受吗?至少应该有某种警告。我只是意外地认出来了。是否还有一种在logscale中绘制零值数据的方法?

谢谢!

P.S。:我希望这适合stackoverflow。我没有找到matplotlib的邮件列表。

1 个答案:

答案 0 :(得分:24)

为此目的最简单的方法是使用“symlog”图。接近0的区间将是线性标度,因此可以显示0。

import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([0,1,2],[10,10,100],marker='o',linestyle='-')
ax.set_yscale('symlog')
ax.set_xscale('symlog')
plt.show()

enter image description here

Symlog设置接近零的小间隔(上下两个)以使用线性比例。这允许事物越过0而不会导致log(x)爆炸(或者转到-inf,而不是)。

这里有一个很好的视觉比较作为答案:https://stackoverflow.com/a/3513150/325565