menu

Questions & Answers

How to create a directories for each dataframe column and plot the column and save plots it into the directory

I have a dataframe. For each coulmn, I want to make a directory (folder) based on the name of the column and then plot the column and save it into the folder. I tried the following code, which makes directories and plots. But the plots are not in their relevant folder. Could anyone please let me know how I can put each plot in its folder?

import matplotlib.pyplot as plt
import pandas as pd
import os

df = pd.DataFrame([[3,4,5], [4,5,10], [6,9,12]], columns=['A', 'B','C'])
for i,j in df.iteritems():
    parent_dir = r"C:\Users\..."
    # Path
    path = os.path.join(parent_dir, i)
    os.mkdir(path)

    fig, ax = plt.subplots(figsize=(4,3))
    ax.plot(j,color='blue')
    plt.savefig(r"C:\Users\...\{}.jpg".format(i))
Answers(1) :

I tried this one too, but its not working

df = pd.DataFrame([[3,4,5], [4,5,10], [6,9,12]], columns=['A', 'B','C'])
for i,j in df.iteritems():
     parent_dir = r"C:\Users\..."

     fig, ax = plt.subplots(figsize=(4,3))
     ax.plot(j,color='blue')
     plt.savefig(r"C:\Users\...\{}".format(os.mkdir(os.path.join(parent_dir, i)))+" 
     {}.jpg".format(i))