pythonpandasmatplotlib

Put specific name on plt.title using DataFrame


I want to plot a graph with the column name in the title. For example:

import pandas as pd
begin_date = '2019-01-01'
    
df = pd.DataFrame ({"date": pd.date_range(begin_date, periods=5),
  "John": [42, 40, 47, 49, 51],
  "Ana": [50, 43, 41, 46,47],
  "Goku": [55, 58, 62, 64, 69],                  
})


import matplotlib.pyplot as plt
plt.plot(df["John"])

I'll plot the graph using this last line with the John values. I want to create something like this:

plt.title("Name of graph: John")

But how do I select the column name and put it in plt.title?

I have to do this in a dataframe which has more than 20 names, and I want to automate this. Is that possible?


Solution

  • You can create a for loop -

    for column in df.columns[1:]:
        plt.figure():
        plt.plot(df["date"], df[column]) 
        plt.show()