python plot intersection of line and data

蓝咒 提交于 2021-02-07 10:28:15

问题


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()

回答1:


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.

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()

And the resulting image:



来源:https://stackoverflow.com/questions/32351310/python-plot-intersection-of-line-and-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!