【问题标题】:How to plot upper and lower boundary with a LINEAR line on a scatter plot?如何在散点图上用 LINEAR 线绘制上下边界?
【发布时间】:2022-03-09 01:35:13
【问题描述】:

我有一个数据框df,其中包含AQ 列。我正在使用此代码在其上绘制一条等式线。

#Actual line of equation, which has to be plotted: Q=alpha*A^beta : ln(Q)=a+b*ln(A) : y = a+b(x)

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

#equation of line
q = alpha * np.power(A,beta)

#plotting the points and line
plt.scatter(A,Q)
plt.plot(A,q, '-r')
plt.yscale('log')
plt.xscale('log')

这给出了以下输出,类似于回归线。

但我有兴趣将方程的同一条线绘制为上下曲线/边界连接两侧最远点(垂直于绿线),如下所示,其斜率与连续绿色的斜率相同行。

【问题讨论】:

  • 这个link 可能会帮助你。

标签: python matplotlib math plot linear-regression


【解决方案1】:

这个想法是首先搜索线和绘图之间的差异最小的点的索引(参见最大值)。至此,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()

【讨论】:

  • pos_min = np.argmin(Q / np.power(A, beta)) 的更新是否适用于您的数据?
猜你喜欢
  • 2022-07-28
  • 1970-01-01
  • 1970-01-01
  • 2022-01-02
  • 1970-01-01
  • 1970-01-01
  • 2014-05-13
  • 2022-12-30
  • 1970-01-01
相关资源
最近更新 更多