用对数标度在散点图上绘制线性回归线困难

2024-06-28 19:25:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样一个数据帧示例:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

df = pd.DataFrame({'a':[0.05, 0.11, 0.18, 0.20, 0.22, 0.27],
                  'b':[3.14, 1.56, 33.10, 430.00, 239.10, 2600.22]})

enter image description here

我想以散点图的形式绘制这些属性,然后显示这些样本的线性趋势线。我需要把y轴上的数据(df['b'])放在对数刻度上

尽管如此,当我试图借助np.polyfit来做这件事时,我得到了一条奇怪的线

# Coefficients for polynomial function (degree 1) 
coefs = np.polyfit(df['a'], df['b'], 1)
fit_coefs = np.poly1d(coefs)

plt.figure()
plt.scatter(df['a'], df['b'], s = 50, edgecolors = 'black') 
plt.plot(df['a'], fit_coefs(df['a']), color='red',linestyle='--')
plt.xlabel('a') 
plt.ylabel('b')
plt.yscale('log')

enter image description here

如果我在绘图之前将df['b]转换为log,我可以得到正确的线性趋势,但是我想用上一个绘图的值显示y轴,而不是像下面这个那样转换为log值:

df['b_log'] = np.log10(df['b'])

coefs = np.polyfit(df['a'], df['b_log'], 1)
fit_coefs = np.poly1d(coefs)

plt.figure()
plt.scatter(df['a'], df['b_log'], s = 50, edgecolors = 'black') 
plt.plot(df['a'], fit_coefs(df['a']), color='red', linestyle='--') 
plt.xlabel('a') 
plt.ylabel('b_log')

enter image description here

所以基本上,我需要一个像上一个一样的图,但是y轴上的值应该像第二个图,我仍然会得到正确的线性趋势。有人能帮我吗


Tags: 数据importlogdfasnpplt线性
1条回答
网友
1楼 · 发布于 2024-06-28 19:25:27

您在那里做了两件不同的事情:首先,将线性曲线拟合到指数数据(这可能不是您想要的),然后将线性曲线拟合到日志数据,这是可以的

为了从对数图中的线性系数中获得线性曲线,您只需执行10**fit_coefs(df['a'])

df['b_log'] = np.log10(df['b'])

coefs = np.polyfit(df['a'], df['b_log'], 1)
fit_coefs = np.poly1d(coefs)

plt.figure()
plt.scatter(df['a'], df['b'], s = 50, edgecolors = 'black') 
plt.plot(df['a'], 10**fit_coefs(df['a']), color='red', linestyle=' ') 
plt.xlabel('a')
plt.ylabel('b_log')
plt.yscale("log")

相关问题 更多 >