0

I have a simple figure which I have used matplotlib.plot function in order to plot it. For example: Simple Graph

Is there a way to extract the data points and paste it (like in matlab) to excel sheet which I didn't know about? I want to assume that many figures were created randomly and I didn't know which data/figure I needed until I see the results.

Community
  • 1
  • 1
mashtock
  • 400
  • 4
  • 21
  • 1
    I don't think so, if you mean to get them from the image. Why you don't save the data points before you generate the `matplotlib` figures? – Minions Jan 12 '20 at 18:27
  • 1
    When plotting such curve, e.g. via `plt.plot(x,y)`, your data is in `x` and `y`. So just save those arrays to a file. – ImportanceOfBeingErnest Jan 12 '20 at 18:37
  • I need to create many figures, but only one of them is the correct one. I wished to avoid being have to add in my GUI a need to select what figure I want to save. – mashtock Jan 13 '20 at 07:25

1 Answers1

2

To extract the data-points, you can assign a variable to your plot:

graph = plt.plot(your_data)
data_points = graph[0].get_data()

Example that extracts the data-points of a line plot and saves them to a csv file:

In[1]:  import matplotlib.pyplot as plt
        import numpy as np

        x = np.linspace(-1, 1, 5)
        y = 2*x + 1
        xy = plt.plot(x, y)
        data = xy[0].get_data()
        print(data)
        plt.show()

        with open('data.csv', 'w') as myfile: 
            writer = csv.writer(myfile)
            writer.writerow(['x', 'y'])
            for i in range(len(data[0])): 
                writer.writerow([data[0][i], data[1][i]])            
Out[1]: (array([-1. , -0.5,  0. ,  0.5,  1. ]), array([-1.,  0.,  1.,  2.,  3.]))

Ioanna
  • 366
  • 1
  • 5
  • Or, in one single line `np.savetxt("data.csv", np.c_[x,y])`. No need to get the data. – ImportanceOfBeingErnest Jan 12 '20 at 19:07
  • In my understanding, mashtock cannot access x, y directly for some reason (?) – Ioanna Jan 12 '20 at 19:15
  • Thank you for the answer, but the question was if there is a way to avoid direct access to the data, but some tool to extract data directly from the figure. Since many figure are being created and only one is needed, I don't know at first what figure is the right one to extract from. I guess this is not possible yet. – mashtock Jan 13 '20 at 07:24
  • There isn't a straightforward way I am afraid. You can either save the graph and add x,y to image's metadata beforehand (example: https://stackoverflow.com/questions/10532614/can-matplotlib-add-metadata-to-saved-figures) or use one of the tools mentioned in some of the answers here: researchgate.net/post/How_can_I_extract_the_values_of_data_plotted_in_a_graph_which_is_available_in_pdf_form – Ioanna Jan 14 '20 at 19:33
  • Thanks so much for this answer. I couldn't find anything else remotely close to this. – Torrjv Apr 24 '20 at 03:23