使用输入数据集,我绘制了一个类似于下图的图表: 我想要拟合多行,如下所示: 然后计算这条线的交点的位置。我通过这个Python代码检查了它,但这不起作用,请帮助我。
dfn=pd.read_csv('input.csv')
x=dfn['X']
y=dfn['Y']
plt.scatter(np.log(x),np.log(y))
num_lines=3
for i in range(num_lines):
coef=np.polyfit(np.log(x),np.log(y),1)
poly1d_fn=np.poly1d(coef)
plt.plot(np.log(x),poly1d_fn(np.log(x)),'r--')
intersection_points=[]
for i in range(num_lines):
for j in range(i+1, num_lines):
coef1=np.polyfit(np.log(x),np.log(y),1)
coef2=np.polyfit(np.log(x),np.log(y),1)
poly1d_fn1=np.poly1d(coef1)
poly1d_fn2=np.poly1d(coef2)
intersection_point=(np.exp((poly1d_fn2-poly1d_fn1).roots),np.exp(poly1d_fn1((poly1d_fn2-poly1d_fn1).roots)))
intersection_points.append(intersection_point)
intersection_df=pd.DataFrame(intersection_points,columns=['X','Y'])
intersection_df.to_csv('intersection_points.csv',index=False)
plt.show()
下面的示例代码标识了线条相交的位置。您需要指定
x
、y
和 n_lines
。代码解决了剩下的问题。
import numpy as np
import matplotlib.pyplot as plt
#
# Synthetic data
#
x = np.linspace(1e-3, 1, 150)
y = np.cos(2 * np.pi * x**2/3)
#Plot the data
f, ax = plt.subplots(figsize=(8, 3))
ax.scatter(x, y, marker='|', s=90)
ax_lims = ax.axis()
#
# Fit lines
#
n_lines = 3
#Divide the x range into n_lines segments
points_per_line = len(x) // n_lines
coefs_per_line = []
for index in range(n_lines):
start = points_per_line * index
end = start + points_per_line
#If this is the last line,
# Use up all the remaining points
is_last_line = (index == n_lines - 1)
if is_last_line:
end = len(x)
x_segment = x[start:end]
y_segment = y[start:end]
#Fit line, and store coefficients
slope, intercept = np.polyfit(x_segment, y_segment, deg=1)
coefs_per_line.append((slope, intercept))
#Plot longer lines to show them intersecting
pad = 10
x_longer = x[start - pad if is_last_line else start : end if is_last_line else end + pad]
ax.plot(x_longer, slope * x_longer + intercept, 'r-', linewidth=2)
if index == 0:
ax.legend(['data', 'linear fits'])
#
# Now, try to find where adjacent lines intersect
#
intersections = []
for index in range(n_lines - 1):
#Get the coefficients for a line, and the line next to it
slope_a, intercept_a = coefs_per_line[index]
slope_b, intercept_b = coefs_per_line[index + 1]
#Solve for the x where line_a = line_b
#No solution when they're parallell (slope_a = slope_b)
if slope_a == slope_b:
intersection_x = np.nan
else:
intersection_x = (intercept_a - intercept_b) / (slope_b - slope_a)
intersections.append(intersection_x)
#
# Finally, add lines showing the locations of the intersections
#
for intersection in intersections:
ax.vlines(intersection, ymin=y.min() - 1, ymax=y.max() + 1, color='k', linestyle=':')
ax.axis(ax_lims)