I have a simple question which I struggle solve though. How can I extract xy values from a line? For example in this line:
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
x1 = [0.1,0.12,0.13,0.18,0.2,0.25,0.27,0.29]
y1 = [1,2,3,4,5,6,7,8]
ax.plot(x1, y1, color='lightblue',linewidth=3)
how can I extract the value of y1 for a non existing x, eg for x=0.23? and also plot it with a dot on the line?
The easiest way is going to be simple linear interpolation.
Given a dataset like the one you have, you can use numpy's interpolation feature to find an arbitrary point within the line.
For instance, given your existing code:
import numpy as np
x1 = [0.1,0.12,0.13,0.18,0.2,0.25,0.27,0.29]
y1 = [1,2,3,4,5,6,7,8]
x = 0.23
y = np.interp(x, x1, y1)
See the documentation on numpy.interp
here: https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.interp.html
If you want to get a little fancier, the scipy.interpolate.interp1d
fucntion is aa bit more complicated, but it presents options like extrapolation, and more advanced line fitting methods than just linear interpolation. See its documentation here: https://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.interp1d.html
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.