X...
X...

Reputation: 183

Acquire x-axis values in Python matplotlib

Before I ask this question, I have already searched the internet for a while without success. To many experts this surely appears to be fairly simple. Please bear with me.

I am having a plot made by matplotlib and it is returned as a plf.Figure. See the following:

def myplotcode():
    x = np.linspace(0, 2*np.pi)
    y = np.sin(x)
    print("x in external function", x)
    y2 = np.cos(x)
    fig = plf.Figure()
    ax = fig.add_subplot(111)
    ax.plot(x, y, 'bo', x, y2,'gs')
    ax.set_ylabel("Some function")
    return fig, ax

What I want to do in the function that call this one is to be able to get all these x values from the returned ax or fig. Well, I understand one simple solution is just to return x array too. However, I am trying to keep the number of returns as small as possible.

So, my question is: Can I acquire this x-axis array from fig or ax?

Thank you so much in advance.

Upvotes: 0

Views: 153

Answers (1)

PerroNoob
PerroNoob

Reputation: 895

You can do:

l = ax.axes.lines[0] # If you have more curves, just change the index
x, y = l.get_data()

That will give you two arrays, with the x and y data

Upvotes: 1

Related Questions