37

I like to switch x axis with y axis after plotting a graph with matplotlib? Any easy way for it? Thanks in advance.

4
  • 2
    stackoverflow.com/questions/15767781/… newer duplicate of this post Commented Apr 7, 2013 at 5:26
  • Could you please add some more information as to what exactly do you mean by "switch x axis with y axis after plotting a graph"? Do you want to plot the axis transposed? Do you want to store transposed values? Commented Mar 25, 2018 at 7:10
  • Possible duplicate of python matplotlib: way to transpose axes Commented Apr 10, 2018 at 18:52
  • I'm wondering what the situation is in which you need this, could you explain that? Commented Jun 24, 2018 at 9:47

3 Answers 3

12

I guess this would be a way to do it in case you really want to change data of an existing plot:

execute this code first to get a figure:

# generate a simple figure
f, ax = plt.subplots()
ax.plot([1,2,3,4,5], [5,6,7,8,9])
ax.set_xlim([0, 10])
ax.set_ylim([0, 10])

and then use this to switch the data of an existing line

# get data from first line of the plot
newx = ax.lines[0].get_ydata()
newy = ax.lines[0].get_xdata()

# set new x- and y- data for the line
ax.lines[0].set_xdata(newx)
ax.lines[0].set_ydata(newy)
Sign up to request clarification or add additional context in comments.

3 Comments

What is the first line this solution refers to? Does it mean that if there are >=2 lines, it will fail?
in case you want to switch multiple lines, simply put it in a loop! (e.g. for line in ax.lines: ...
only work if axis have the same dtype tho!
-1

You can simply switch x and y parameters in the plot function:

I[3]: x = np.linspace(0,2*np.pi, 100)

I[4]: y = np.sin(x)

I[5]: plt.plot(x,y)

I[6]: plt.figure(); plt.plot(y,x)

1 Comment

Thanks, but it is not the answer I am seeking. I am asking how to switch x and y axes after I have plotted all data.
-1

Rotate the monitor 90 degrees and look at its mirror image. An O(1) solution.

1 Comment

Love the joke ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.