Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
259 views
in Technique[技术] by (71.8m points)

python - How to extract points from a graph?

I have a question.

I have plotted a graph using Matplotlib like this:

from matplotlib import pyplot
import numpy
from scipy.interpolate import spline

widths = numpy.array([0, 30, 60, 90, 120, 150, 180])
heights = numpy.array([26, 38.5, 59.5, 82.5, 120.5, 182.5, 319.5])

xnew = numpy.linspace(widths.min(),widths.max(),300)
heights_smooth = spline(widths,heights,xnew)

pyplot.plot(xnew,heights_smooth)
pyplot.show()

Now I want to query a height value using width value as an argument. I cannot seem to find how to do that. Please help! Thanks in advance!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

plot() returns a useful object: [<matplotlib.lines.Line2D object at 0x38c9910>]
From that we can get x- and y-axis values:

import matplotlib.pyplot as plt, numpy as np
...
line2d = plt.plot(xnew,heights_smooth)
xvalues = line2d[0].get_xdata()
yvalues = line2d[0].get_ydata()

Then we can get the index of one of the width values:

idx = np.where(xvalues==xvalues[-2]) # this is 179.3979933110368
# idx is a tuple of array(s) containing index where value was found
# in this case -> (array([298]),)

And the corresponding height:

yvalues[idx]
# -> array([ 315.53469])

To check we can use get_xydata():

>>> xy = line2d[0].get_xydata()
>>> xy[-2]
array([ 179.39799331,  315.53469   ])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...