Skip to content
Advertisement

Changing plot title through loop

I am new to python and need your help. I have several dataframes. Each dataframe is for one day. So I am using for loop to plot for all dataframe. For each plot I want to add the date in my title. Can anyone help me. I have created a variable ‘date_created and assigned the dates which I want. I want my title to look like below : ‘Voltage vs time 28-01-2022’

for df in (df1,df2,df3,df4,df5,df6,df7,df8):
    y = df[' Voltage'] 
    x = df['time']
    date_created = [ '28-01-2022, 29-01-2022, 30-01-2022, 31-08-2022, 01-02-2022, 02-02-2022, 03-02-2022, 04-02-2022' ]
    fig, ax = plt.subplots(figsize=(18,7))
    plt.plot(x,y, 'b') 
    plt.xlabel("time")
    plt.ylabel(" Voltage [V]")
    plt.title("Voltage vs time")

Advertisement

Answer

To make code work more effective it would be better to create a dictionary of dataframes and dates (if you haven’t got date column in your dataframe).

dict = {df1: '28-01-2022', df2: '29-01-2022', df3: '30-01-2022'}

Than we will use for loop for elements of this dictionary

for key, value in dict.items():
      y = key['Voltage'] 
      x = key['time'] 
      fig, ax = plt.subplots(figsize=(18,7))
      plt.plot(x,y, 'b') 
      plt.xlabel("time")
      plt.ylabel(" Voltage [V]")
      plt.title(f"Voltage vs time {value}")

Hope this will work for you!

Advertisement