pythonpandasmatplotlibseries

How to reverse axes when plotting a Series?


How to swap x and y axes when plotting a time Series? Either by manipulating the Series or with Series.plot(). I know it's possible for a DataFrame, by plotting its transpose.

import pandas as pd
import numpy.random as npr

def rand_data(n=5):
    return npr.choice([1,5,6,8,9], size=n)

npr.seed(0)
n = 8
index = pd.date_range('2013/01/31 09:10:12', periods=n, freq='ME')
s = pd.Series(index=index, data=rand_data(n))
s.plot()

enter image description here


Solution

  • Do you mean swapping the x and y data like this

    import matplotlib.pyplot as plt
    
    fig, ax = plt.subplots()
    ax.plot(s.values, s.index)
    plt.show()
    

    or inverting the data in every axis like this

    import matplotlib.pyplot as plt
    
    fig, ax = plt.subplots()
    ax.plot(s.index, s.values)
    ax.invert_xaxis()
    ax.invert_yaxis()
    plt.show()
    

    ?

    EDIT: swapping x and y data without importing matplotlib backend directly:

    sframe = s.to_frame().reset_index()
    sframe.plot(x=sframe.columns[1], y=sframe.columns[0])