Extract data from a plot

Question:

I’m new in Python. I would like to know if there is a way that allows me to extract data from a plot, and save them in two different arrays.
I try to explain me better: if I have for example a plot like the one in the script, that is a Gaussian:

import matplotlib.pyplot as plt
import numpy as np

def myDGauss(x,I1,I2,sigma1,sigma2):
    return I1*np.exp(-x*x/(2*sigma1*sigma1)) + I2*np.exp(-x*x/(2*sigma2*sigma2))

colPosmm = np.array([3.28, 3.13, 3.08, 3.03, 2.98, 2.93, 2.88, 2.83, 2.78, 2.73, 2.68, 2.63, 2.58, 2.53, 2.48, 2.43, 2.38, 2.33, 2.28, 2.23, 2.18, 2.13, 2.08, 2.03, 1.98, 1.93, 1.88, 1.83, 1.78, 1.73, 1.68, 1.63, 1.58, 1.53, 1.48, 1.43, 1.38, 1.33, 1.28, 1.23, 1.18, 1.13, 1.08, 1.03, 0.98, 0.93, 0.88, 0.83, 0.78, 0.73, 0.68, 0.63, 0.58, 0.53, 0.48, 0.43, 0.38, 0.33, 0.28, 0.23, 0.18, 0.13, 0.08, 0.03])
popt = np.array([ 0.2375745, 0.74777219, -0.57253271, 1.23600569])
xfull = np.linspace(-9,9,2*len(colPosmm))
plt.plot(xfull, myDGauss(xfull, *popt), '--')
plt.show()

If I have a plot of which I don’t know previously the values of the axis, is there a way to extract them? Is there a way to save the value of both axis in two different array?. The script is only an example, I’m checking a method that could be applied to different plots.
Could any one help me, please? Thanks!

Asked By: XaBla

||

Answers:

If you have a plot object, plt.axis() gives you the spans for x and y axes, respectively.

print(plt.axis())
# (-9.9, 9.9, -0.049115284357094655, 1.0314209715494458)

Given code already includes values for both axes,

print(xfull)
# array([-9. , -8.85826772, -8.71653543, -8.57480315, -8.43307087 ...

yfull = myDGauss(xfull, *popt)

print(yfull)
# array([2.29354430e-12, 5.25138995e-12, 1.18667233e-11, 2.64652970e-11 ...

If you want to see the corresponding x, y values,

print(list(zip(xfull, yfull)))
# [(-9.0, 2.2935442971371085e-12), (-8.858267716535433, 5.251389947559247e-12) ...
Answered By: BcK
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.