如何通过登录Seaborn来相等地缩放x和y轴?

时间:2018-12-29 19:31:54

标签: python matplotlib linear-regression seaborn logarithm

我想在Seaborn中创建具有线性回归的regplot,并通过对数均等缩放两个轴,以使回归保持直线。

一个例子:

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

1 个答案:

答案 0 :(得分:1)

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

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

警告:您的x条目之一是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