python - Seaborn中如何通过log对x轴和y轴进行等比例缩放?

标签 python matplotlib linear-regression seaborn logarithm

我想在 Seaborn 中创建一个具有线性回归的正则图,并按对数平均缩放两个轴,以使回归保持直线。

一个例子:

import matplotlib.pyplot as plt
import seaborn as sns

some_x=[0,1,2,3,4,5,6,7]
some_y=[3,5,4,7,7,9,9,10]

ax = sns.regplot(x=some_x, y=some_y, order=1)
plt.ylim(0, 12)
plt.xlim(0, 12)
plt.show()

我得到了什么:

Linear regression

如果我按对数缩放 x 和 y 轴,我希望回归保持直线。我尝试过的:

import matplotlib.pyplot as plt
import seaborn as sns

some_x=[0,1,2,3,4,5,6,7]
some_y=[3,5,4,7,7,9,9,10]

ax = sns.regplot(x=some_x, y=some_y, order=1)
ax.set_yscale('log')
ax.set_xscale('log')
plt.ylim(0, 12)
plt.xlim(0, 12)
plt.show()

它的外观:

Linear regression becomes a curve

最佳答案

问题是您正在以常规比例拟合数据,但后来您将轴转换为对数比例。因此,线性拟合在对数尺度上将不再是线性的。

您需要的是将数据转换为对数刻度(以 10 为底),然后执行线性回归。您的数据当前是一个列表。如果将列表转换为 NumPy 数组,则可以轻松将数据转换为对数比例,因为这样您就可以利用矢量化操作。

警告:您的 x-entry 之一是 0,其日志未定义。您将在那里遇到警告。

import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np

some_x=np.array([0,1,2,3,4,5,6,7])
some_y=np.array([3,5,4,7,7,9,9,10])

ax = sns.regplot(x=np.log10(some_x), y=np.log10(some_y), order=1)

使用 NumPy polyfit 的解决方案,其中从拟合中排除 x=0 数据点

import matplotlib.pyplot as plt
import numpy as np

some_x=np.log10(np.array([0,1,2,3,4,5,6,7]))
some_y=np.log10(np.array([3,5,4,7,7,9,9,10]))

fit = np.poly1d(np.polyfit(some_x[1:], some_y[1:], 1))

plt.plot(some_x, some_y, 'ko')
plt.plot(some_x, fit(some_x), '-k')

enter image description here

关于python - Seaborn中如何通过log对x轴和y轴进行等比例缩放?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53972754/

相关文章:

python - 余弦波的贝叶斯拟合花费的时间比预期的要长

python - 值错误 : x and y must have same first dimension

python - 如何在极坐标 matplotlib 图中旋转刻度标签?

Python,根据应用于相同长度的现有列表的条件创建新列表

python - 绘制时间序列?

python - 第一次使用 matplotlib.pyplot.scatter 函数时出错

Mysql多变量线性回归

python-3.x - 如何从 numpy 数组中输入数据来训练 CNTK 回归模型

python - 导入错误 : cannot import name 'Testcase' from 'unittest'

python - 按下按键时做一些事情 | Python