log'与'symlog'的区别是什么?

136 投票
3 回答
80429 浏览
提问于 2025-04-16 01:40

matplotlib 这个库里,我可以用 pyplot.xscale() 或者 Axes.set_xscale() 来设置坐标轴的缩放方式。这两个函数都可以接受三种不同的缩放方式:'linear'(线性)| 'log'(对数)| 'symlog'(对称对数)。

那么 'log''symlog' 之间有什么区别呢?我做了一个简单的测试,发现它们看起来完全一样。

我知道文档上说它们接受不同的参数,但我还是不太明白它们之间的区别。有没有人能给我解释一下?如果能提供一些示例代码和图形,那就更好了!(还有:'symlog' 这个名字是怎么来的?)

3 个回答

14

这里有一个需要使用symlog的例子:

最初的图表,没有缩放。注意有多少点聚集在x大约为0的位置。

    ax = sns.scatterplot(x= 'Score', y ='Total Amount Deposited', data = df, hue = 'Predicted Category')

[未缩放

对数缩放的图表。所有数据都压缩在一起了。

    ax = sns.scatterplot(x= 'Score', y ='Total Amount Deposited', data = df, hue = 'Predicted Category')

    ax.set_xscale('log')
    ax.set_yscale('log')
    ax.set(xlabel='Score, log', ylabel='Total Amount Deposited, log')

对数缩放

为什么会压缩在一起呢?因为x轴上的一些值非常接近或者等于0。

使用symlog缩放的图表。一切都恢复正常了。

    ax = sns.scatterplot(x= 'Score', y ='Total Amount Deposited', data = df, hue = 'Predicted Category')

    ax.set_xscale('symlog')
    ax.set_yscale('symlog')
    ax.set(xlabel='Score, symlog', ylabel='Total Amount Deposited, symlog')

symlog缩放

29

symlog 就像是对数图,但它允许你定义一个接近零的值范围,在这个范围内图形是线性的,这样就可以避免图形在零附近变得无穷大。

来源于 http://matplotlib.sourceforge.net/api/axes_api.html#matplotlib.axes.Axes.set_xscale

在对数图中,你永远不能有零值,如果有一个值接近零,它会在图的底部猛然下降(无限往下),因为当你计算“接近零的对数”时,你会得到“接近负无穷大”。

symlog 可以帮助你在需要绘制对数图的情况下,处理那些可能会下降到零或者接近零的值,但你仍然想以有意义的方式在图上展示这些值。如果你需要使用 symlog,你会知道的。

238

我终于找到了一些时间来做实验,以便理解它们之间的区别。以下是我发现的内容:

  • log 只允许正值,并且让你选择如何处理负值(可以选择 maskclip)。
  • symlog 意思是 对称对数,它允许正值和负值。
  • symlog 允许你设置一个范围,在这个范围内,图表将是线性的,而不是对数的。

我觉得用图形和例子来解释会更容易理解,所以我们来试试:

import numpy
from matplotlib import pyplot

# Enable interactive mode
pyplot.ion()

# Draw the grid lines
pyplot.grid(True)

# Numbers from -50 to 50, with 0.1 as step
xdomain = numpy.arange(-50,50, 0.1)

# Plots a simple linear function 'f(x) = x'
pyplot.plot(xdomain, xdomain)
# Plots 'sin(x)'
pyplot.plot(xdomain, numpy.sin(xdomain))

# 'linear' is the default mode, so this next line is redundant:
pyplot.xscale('linear')

使用'线性'缩放的图

# How to treat negative values?
# 'mask' will treat negative values as invalid
# 'mask' is the default, so the next two lines are equivalent
pyplot.xscale('log')
pyplot.xscale('log', nonposx='mask')

使用'对数'缩放和非正值处理为'mask'的图

# 'clip' will map all negative values a very small positive one
pyplot.xscale('log', nonposx='clip')

使用'对数'缩放和非正值处理为'clip'的图

# 'symlog' scaling, however, handles negative values nicely
pyplot.xscale('symlog')

使用'symlog'缩放的图

# And you can even set a linear range around zero
pyplot.xscale('symlog', linthreshx=20)

使用'symlog'缩放,但在(-20,20)范围内是线性的图

为了完整起见,我使用了以下代码来保存每个图形:

# Default dpi is 80
pyplot.savefig('matplotlib_xscale_linear.png', dpi=50, bbox_inches='tight')

记得你可以通过以下方式更改图形大小:

fig = pyplot.gcf()
fig.set_size_inches([4., 3.])
# Default size: [8., 6.]

(如果你对我自己回答自己的问题有疑问,可以阅读 这个

撰写回答