这个想法是首先搜索线和绘图之间的差异最小的点的索引(参见最大值)。至此,alpha_min 可以这样计算:
Q[pos_min] == alpha_min * np.power(A[pos_min], beta),因此
alpha_min = Q[pos_min] / np.power(A[pos_min], beta).
由于这些线可以从原始点延伸很远,它可以帮助恢复 x 和 y 限制(从而将绘图剪切到原始区域)。
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
df = pd.DataFrame()
df['A'] = 10 ** np.random.uniform(0, 1, 1000) ** 2
df['Q'] = 10 ** np.random.uniform(0, 1, 1000) ** 2
x = np.log(df['A'])
y = np.log(df['Q'])
# deriving b,a
b, a = np.polyfit(np.log(x), y, 1)
# deriving alpha and beta. By using a = ln(alpha); b = beta - 1
alpha = np.exp(a)
beta = b + 1
Q = df['Q'].values
A = df['A'].values
# plotting the points and line
plt.yscale('log')
plt.xscale('log')
plt.scatter(A, Q, color='b')
# equation of line
xmin, xmax = plt.xlim() # the limits of the x-axis for drawing the line
x = np.linspace(xmin, xmax, 50)
q = alpha * np.power(x, beta)
plt.plot(x, q, '-r')
ymin, ymax = plt.ylim() # store the limits of the scatter and line plot so they can be restored later
pos_min = np.argmin(Q / np.power(A, beta))
pos_max = np.argmax(Q / np.power(A, beta))
alpha_min = Q[pos_min] / np.power(A[pos_min], beta)
alpha_max = Q[pos_max] / np.power(A[pos_max], beta)
# plt.scatter(A[pos_min], Q[pos_min], s=100, fc='none', ec='r', lw=3)
# plt.scatter(A[pos_max], Q[pos_max], s=100, fc='none', ec='g', lw=3)
plt.plot(x, (alpha_max) * np.power(x, beta), '--r')
plt.plot(x, (alpha_min) * np.power(x, beta), '--r')
plt.xlim(xmin, xmax) # restore the limits of the scatter plot
plt.ylim(ymin, ymax)
plt.show()