python绘制线和数据的交集 [英] python plot intersection of line and data
问题描述
我有一个看起来像这样的数据文件:
I have a data file that looks something like this:
0 0
0.1 0.1
0.2 0.2
0.3 0.3
0.4 0.31
0.5 0.32
0.6 0.35
我想找到与斜率相交的值.到目前为止,我的代码如下:
And I would like to find the the value that intersects with a slope. My code looks like this so far:
from numpy import *
from pylab import *
data = loadtxt('test.dat')
strain = data[:,0]
stress = data[:,1]
E = 1
y = [0, 0.5]
x = 0.2, ((y[1] - y[0])/E+0.2)
figure(num=None, figsize=(10, 6), dpi=100, facecolor='w', edgecolor='k')
plot(strain, stress)
plot(x, y)
show()
推荐答案
您可以使用scipy中的 interp1d
函数在每组点之间创建线性插值.interp1d
接受 x 和 y 值并返回一个函数,该函数接受一个 x 值并返回相应的 y 值.一旦有了应力和y的函数,就需要找出它们相交的位置.一种有效的方法是使用二分法之类的方法,它可以找到零点.
You can use the interp1d
function from scipy to create a linear interpolation between each set of points. interp1d
takes x and y values and returns a function that takes an x value and returns the corresponding y value. Once you have a function for stress and for y, you need to figure out where those intersect. One way to do this efficiently is with something like the bisection method, which finds zeros.
这是代码:将numpy导入为np
Here's the code: import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import interp1d
from scipy.optimize import bisect
data = '''0 0
0.1 0.1
0.2 0.2
0.3 0.3
0.4 0.31
0.5 0.32
0.6 0.35'''
data = [line.split() for line in data.split('\n')]
data = np.array(data, dtype = 'float')
strain = data[:,0]
stress = data[:,1]
E = 1
y = [0, 0.5]
x = 0.2, ((y[1] - y[0])/E+0.2)
#use interp1d to get interpolated points
y = interp1d(x, y)
stress = interp1d(strain, stress)
#set starting points
x1 = max(x[0], strain[0])
x2 = min(x[-1], strain[-1])
max_err = .01
#create function
f = lambda x : stress(x) - y(x)
#find x1 where f(x1) = 0
x1 = bisect(f, x1, x2, xtol = .001)
y1 = stress(x1)
plt.figure(num=None, figsize=(10, 6), dpi=100, facecolor='w', edgecolor='k')
plt.plot(strain, stress(strain))
plt.plot(x, y(x))
plt.scatter(x1, y1)
plt.show()
和生成的图像:
这篇关于python绘制线和数据的交集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!