如何找到图形的斜率

17 投票
2 回答
72291 浏览
提问于 2025-04-15 19:09

这是我的代码:

import matplotlib.pyplot as plt
plt.loglog(length,time,'--')

其中,length和time是两个列表。

我该如何找到这个图表的线性拟合斜率呢?

2 个回答

0

你需要利用 np.array 把你的列表转换成数组,然后再进行其他计算:

import matplotlib.pyplot as plt
import numpy as np

Fitting_Log = np.polyfit(np.array(np.log(length)), np.array(np.log(time)), 1)   
Slope_Log_Fitted = Fitting_Log[0]

Plot_Log = plt.plot(length, time, '--')
plt.xscale('log')
plt.yscale('log')
plt.show()
33

如果你安装了matplotlib,那么你也必须安装numpy,因为它是一个依赖库。所以,你可以使用 numpy.polyfit 来找到斜率:

import matplotlib.pyplot as plt
import numpy as np

length = np.random.random(10)
length.sort()
time = np.random.random(10)
time.sort()
slope, intercept = np.polyfit(np.log(length), np.log(time), 1)
print(slope)
plt.loglog(length, time, '--')
plt.show()

撰写回答