Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a title to a pandas dataframe plot

Able to create 2 nice time series graphs, but plot.title() is not working. How can this be fixed?

import pandas as pd 
import datetime 
import matplotlib.pyplot as plt 

if __name__ == '__main__':
    index_data = pd.read_csv('comparison_dataset.csv')
    index_data['DATE'] = pd.to_datetime(index_data['DATE'])
    index_data.set_index('DATE', inplace=True)

    print(index_data)

    df = pd.DataFrame(index_data)
    print(df)

    plt.title('S&P/Case-Shiller U.S. National Home Price Index')
    plt.figure()
    df.plot()
    plt.legend(loc = 'best')
    plt.show()


    #now create second data frame with level values and growth rates
    df2=df

    index_data['pct_change_actuals_2']=(df2.HPI_Actuals - df2.HPI_Actuals.shift(4)) /   df2.HPI_Actuals;
    index_data['pct_change_F_VECM']=(df2.HPI_F_VECM - df2.HPI_F_VECM.shift(4)) / df2.HPI_F_VECM;
    index_data['pct_change_F_VAR']=(df2.HPI_F_VAR - df2.HPI_F_VAR.shift(4)) / df2.HPI_F_VAR;
    index_data['pct_change_F_ML']=(df2.HPI_F_ML - df2.HPI_F_ML.shift(4)) / df2.HPI_F_ML;
    index_data['pct_change_F_ARIMA']=(df2.HPI_F_ARIMA - df2.HPI_F_ARIMA.shift(4)) /     df2.HPI_F_ARIMA;

    print(df2)

    df3= df2[['pct_change_actuals_2',   'pct_change_F_VECM','pct_change_F_VAR','pct_change_F_ML','pct_change_F_ARIMA']]
    plt.title('S&P/Case-Shiller U.S. National Home Price Index Yearly Change')
    plt.figure()
    df3.plot()
    plt.legend(loc = 'best')
    plt.show()

First series graph

Second series graph

like image 715
UBS Avatar asked Sep 18 '25 23:09

UBS


1 Answers

Your plt.title call happens before the figure is created (with plt.figure()). This cannot work. You should move the plt.title command after the graph df.plot().

Also, if you want a figure title, the command is plt.suptitle. plt.title works at the axes level.

like image 127
mozway Avatar answered Sep 21 '25 15:09

mozway