First and foremost, I'd like to precise that I am no expert in Python and still learning how to use pandas. I dig through older posts but I don't find a suitable answer.
I've been trying to code a data analysis of 92 contracts. For each of them, I'd like to plot a specific analysis (taking some columns of a same dataframe each time) and save each analysis in a different folder (Analysis 1, Analysis 2, ...).
So far, I am facing many difficulties. Thus, before focusing on WHAT to plot, I'd like to understand how to code the saving of each plot in a different .png file each time. The code I've tried does not seem to save anything as when I go to the folder it's empty.
Thanks to waykiki's help, I've been able to update my code. Now I know how to create as many folders as analysis I produce. Yet, I do not seem to understand how to code the plot of 92 graphs per analysis. My code now looks like this:
import pandas as pd
import matplotlib.pyplot as plt
import os
# Folder in which I want the analyses to be saved
URL5 = r"C:\Users\A\AppData\Local\Programs\Python\Python39"
# 1 graph per ID_Contrat (thus, 92 graphs)
groups = outer_merged_df.groupby("ID_Contrat") #where outer_merged_df is my dataframe
# How to name each plot.
List_ID_Contrat = outer_merged_df["ID_Contrat"].tolist()
def create_plot(file_name, x, y):
# Create your plot. It is my understanding that here I should just give the x and the y I want to plot.
fig = plt.figure()
plt.plot(x, y, color = "red", kind = "line", legend = "true", linewidth = 2)
plt.savefig(file_name)
plt.show()
def main():
# must be full-path.
parent_folder = URL5
# move to parent directory
os.chdir(parent_folder)
# I want file_name to be different for each graph
extension = ".png"
# 5 = how many analyses I want to do
for i in range(5):
for name in List_ID_Contrat :
file_name = "Analyse" + str[i+1] "{}" + extension.format(name) # I want file_name to be different for each graph and looking like "Analyse i Contrat XX"
# Create a new folder
folder_name = 'Analysis ' + str(i+1)
os.mkdir(folder_name)
full_file_name = folder_name + '/' + file_name
x = np.linspace(1,100,100)
y = np.random.random(100)
create_plot(full_file_name, x, y)
print("plot "+ savefile +" finished".format(name))
if __name__ == "__main__":
main()
Yet, when I run my code, it does not plot 92 graphs nor want to create the folders anymore (though it did using Waykiki's method). The for loop is broken during hte first round (i only get the folder "Analysis 1") I get the Error Message:
AttributeError: 'Line2D' object has no property 'kind'
Could you please explain to me how I can save the graphs ? I am getting lost ..
Thanks