pythonpandasfor-loopmatplotlibsavefig

savefig png where its file name is exactly the same as the excel sheet for loop


I have an excel (screen shot below) file with two sheets and tried to plot the data from each sheets using for in loop. I already succeeded creating two plots from these two sheets using this code below.

enter image description here

The problem is I also want to automatically save the plots into different png files where each png file name is exactly as the same as the sheet name from the excel. The png file name that I got is '83' and '95' not 'E1' nor 'E4. Screenshot below. enter image description here'

Before the savefig there is two more for in loop for annotating. Does these two loops variable need to be changed?

thank you in advance

import pandas as pd
import matplotlib.pyplot as plt

path ='F:\Backup\JN\TOR\TOR HLS.xlsx'
data= pd.ExcelFile(path)

sheets = data.sheet_names
    
for i in sheets:
    well=pd.read_excel(data, sheet_name=i)
    plt.plot(well['T'], well['mdpl pt'], marker='o', color='blue')
    plt.plot(well['P'], well['mdpl pt'], marker='o', color='red')
    for i, txt in enumerate(well['csg']):
        plt.annotate(txt, ((well['x csg']+5)[i], well['mdpl csg'][i]))
    for i, txt in enumerate(well['liner']):
        plt.annotate(txt, ((well['x liner']+5)[i], well['mdpl liner'][i]))
    plt.savefig(str(i), dpi=300, transparent='True')
    plt.close(i)

Solution

  • I tried a snippet following your code and it works well for me and it creates 2 images with name E3 and E4 as my sheet names are E3 and E4. I have attached my excel data as output also. Please check it too

    import pandas as pd
    import matplotlib.pyplot as plt
    import numpy as np
    path ='HLS.xlsx'
    data= pd.ExcelFile(path)
    sheets = data.sheet_names
    print(sheets)
    #['E3', 'E4']
    
    for i in sheets:
        well=pd.read_excel(data, sheet_name=i)
        print(well)
        plt.plot(well['A'], well['B'], color='blue')
        plt.savefig(i)
        plt.close(i)
    
    #well
    #E3 first #E4 second
    """   A  B
       0  1  6
       1  2  5
       2  3  4
       3  4  3
       4  5  2
       5  6  1
          A  B
       0  6  1
       1  5  2
       2  4  3
       3  3  4
       4  2  5
       5  1  6"""