0

I already checked out this question, but it didn't solve my problem.

Hello! I have a pyplot figure:

def foo(data): fig, ax = plt. subplots(figsize=(20, 10), dpi=100)

    xaxis = (list with x values)
    yaxis = (numpy array with y values)
    ax.plot(xaxis, yaxis)

I would like foo() to return the x and y values. I understand that I could just do

return xvalues, yvalues

But I'd like to extract the data from the figure.

I've tried my best to read the pyplot documentation, but I'm still pretty new to it, so if I'm doing something stupid, please let me know!

EDIT: I wasn't really descriptive enough, sorry. I'm trying to write a unit test for a module where one of the methods is to generate and save a graph. foo() doesn't necessarily have to return the x and y data, I'd just like it to return something I can use to make sure it generated the plot properly. I'm aware that matplotlib has testing stuff built in, but I would have to restructure a lot of my code to make it work.

Community
  • 1
  • 1
  • 3
    not using the data that you already have is pretty silly, yes. If you have `xvalues` and `yvalues` then *use* them. Putting that data somewhere else and then trying to get it from somewhere else instead of where you have it in the first place is just plain silly. – Wayne Werner Jul 12 '16 at 21:12
  • 1
    You most certainly missed to explain your full problem, otherwise your question doesn't make sense (as @Wayne said: just return your raw data). What have you not told us? I suspect an XY problem: you're trying to solve another problem, and this kludge you're trying to do is an effort to solve a derived problem. If you tell as what you're really after, we can help you do it properly. – Andras Deak -- Слава Україні Jul 12 '16 at 21:19
  • From your edit, I think you are violating one of the principles of testing, which is isolate your system under test (SUT) from external depenencies. You need to test _your code_, and not its interaction with external libraries, and even less the external libraries themselves. – heltonbiker Jul 14 '16 at 16:21

1 Answers1

2

I think the following code does what you want for a simple line plot:

import numpy as np
import matplotlib.pyplot as plt

def foo(xaxis, yaxis): 
    fig, ax = plt. subplots(figsize=(20, 10), dpi=100)
    curve = ax.plot(xaxis, yaxis)
    # curve = [Line2D object]
    return curve[0].get_xdata(), curve[0].get_ydata()

x,y = foo(range(10), range(0,20,2))
print(x,y)
j_4321
  • 15,431
  • 3
  • 34
  • 61