How to switch axes in matplotlib?

前端 未结 2 838
再見小時候
再見小時候 2021-01-17 07:58

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

相关标签:
2条回答
  • 2021-01-17 08:04

    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)
    
    0 讨论(0)
  • 2021-01-17 08:06

    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)
    
    0 讨论(0)
提交回复
热议问题