Search code examples
pandasmatplotlibtimeserieschart

How to draw a dataframe column of dtype = datetime64[ns] on x- axis of a matplot?


I wanted to draw two time series on the same plot of matplotlib. I have a pandas dataframe as shown here Where the Date column is of dtype= datetime64[ns] as x-axis and Close, Open column are type=np.float64 as y-axis

Im trying the code

import matplotlib as plt
plt.xticks( df['Index'].values)
plt.plot(df['Close'])
plt.plot(df['Open'])
plt.show()

But it is showing errors. Where should I improve ??


Solution

  • To plot only some columns of your df(in this example 'col1' and 'col2'), you can do so:

    import matplotlib.pyplot as plt
    import pandas as pd
    df = pd.DataFrame([[10,11, 3,'2018-04-02 20:30'], [15, 20, 5, '2018-04-02 20:31'], [20, 25, 6, '2018-04-02 20:40'], [10, 12, 8, '2018-04-02 20:45']], columns = ['col1', 'col2', 'col3' ,'Dates'])
    print (df)
    
       col1  col2  col3             Dates
    0    10    11     3  2018-04-02 20:30
    1    15    20     5  2018-04-02 20:31
    2    20    25     6  2018-04-02 20:40
    3    10    12     8  2018-04-02 20:45
    
    df['Dates'] = pd.to_datetime(df['Dates'], format='%Y-%m-%d %H:%M')
    df.set_index(['Dates'],inplace=True)
    df.loc[:,['col1','col2']].plot()
    plt.show()
    

    In your case this should work:

    df.loc[:,['Open','Close']].plot()