简体   繁体   English

如何通过登录 Seaborn 等比例缩放 x 和 y 轴?

[英]How to scale the x and y axis equally by log in Seaborn?

I want to create a regplot with a linear regression in Seaborn and scale both axes equally by log, such that the regression stays a straight line.我想在 Seaborn 中创建一个带有线性回归的 regplot,并按对数对两个轴进行平均缩放,以便回归保持一条直线。

An example:一个例子:

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

What I get:我得到的:

线性回归

If I scale the x and y axis by log, I would expect the regression to stay a straight line.如果我按对数缩放 x 和 y 轴,我希望回归保持直线。 What I tried:我试过的:

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

How it looks:它的外观:

线性回归变成曲线

The problem is that you are fitting to your data on a regular scale but later you are transforming the axes to log scale.问题是您正在以常规比例拟合数据,但后来您将轴转换为对数比例。 So linear fit will no longer be linear on a log scale.所以线性拟合在对数尺度上不再是线性的。

What you need instead is to transform your data to log scale (base 10) and then perform a linear regression.相反,您需要的是将数据转换为对数刻度(以 10 为底),然后执行线性回归。 Your data is currently a list.您的数据目前是一个列表。 It would be easy to transform your data to log scale if you convert your list to NumPy array because then you can make use of vectorised operation.如果将列表转换为 NumPy 数组,将数据转换为对数刻度会很容易,因为这样您就可以使用矢量化操作。

Caution: One of your x-entry is 0 for which log is not defined.注意:您的 x 条目之一是0 ,未定义日志。 You will encounter a warning there.您将在那里遇到警告。

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)

Solution using NumPy polyfit where you exclude x=0 data point from the fit使用 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')

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM