Search code examples
pythonfor-loopmatplotlibiterated-function

how to plot line graphs with an iterate method and assign proper labels at each of them


This is the dataset I am working on

Update  Pb95    Pb98    diesel  heating oil
0   6/2/2022    7519    8311    7172    5582
1   6/1/2022    7406    8194    6912    5433
2   5/31/2022   7213    7950    6754    5394
3   5/28/2022   7129    7864    6711    5360
4   5/27/2022   7076    7798    6704    5366
5   5/26/2022   6895    7504    6502    5182
6   5/25/2022   6714    7306    6421    5130
7   5/24/2022   6770    7358    6405    5153
8   5/21/2022   6822    7421    6457    5216
9   5/20/2022   6826    7430    6523    5281

I am attempting to create some elegant graphs in order to represent the relationship between time vs price change. I have use the following code for a single graph

    import matplotlib.pyplot as plt
    
    plt.plot(df['Update'], df['Pb95'], label='sales', linewidth=3)
    plt.rcParams["figure.figsize"] = (8,8)
    
    #add title and axis labels
    plt.title('Fuels price by Date')
    plt.xlabel('Date')
    plt.ylabel('Price (PLN)')
    
    
    #add legend
    plt.legend()
    
    #display plot
    plt.show() 

Now I would have liked to plot the lines for each fuel in different plots by using a for a loop. I have used the following code:

df_columns = df.iloc[:,1:6]
for i in df_columns: 
    plt.plot(df['Update'], df[i], label='sales', linewidth=3)
    plt.title('Fuels price by Date')
    plt.xlabel('Date')
    plt.ylabel('Price (PLN)')


plt.legend()    
plt.show() 

I have obtained a unique plot

enter image description here

but now I would like, where I would like to assign the proper name of fuel to each of the lines. Is there anyone that could help with one of the two ways I would like (separate or in the same plot) I would like to represent this relationship?

I would like above all to learn how to assign labels (for one or the other way to plot a graph) by an iterated method.

Thanks


Solution

  • You can do that by modifying your code slightly. I'm using the dataframe exerpt you provided.

    for column in df.columns[1:]: 
        plt.plot(df['Update'], df[column], label=column, linewidth=3)
        plt.title('Fuels price by Date')
        plt.xlabel('Date')
        plt.ylabel('Price (PLN)')
    
    
    plt.legend()    
    plt.show() 
    

    Gives this:

    enter image description here

    Alternatively, you can do this by pandas' own plot method.

    df.plot.line(x='Update', y=['Pb95', 'Pb98', 'diesel', 'heating oil'])
    

    Gives this:

    enter image description here