Home > Software design >  How to save some image from plot to the file in my desktop?
How to save some image from plot to the file in my desktop?

Time:06-26

When I run this part of code (run a function) and then I see my folder in my desktop , there is nothing in there. Why? I expect that I see some PNG file in my folder of my desktop but I can't see them and they don't save in my folder

def curve(lisst , m):
  for i in lisst:
    if i in m.columns :
      r = plt.figure()
      plt.title(i)
      plt.plot(m.Time , m[i])
      plt.savefig(r"C:\Users\parsa\Desktop\kholase\image{}.png".format(i))

CodePudding user response:

It is better to first check your current working directory using

import os
os.getcwd

Then check if the plot is saved there with the name you are specifying or not.

CodePudding user response:

Seems like you might just have the wrong command on plt.save, try plt.savefig instead?

EDIT:

Might be a few things that are going wrong here, but assuming "lisst" is a list of column names and "m" is a pandas dataframe with "Time" as a datetime column (not index!), this might work:

# Set path explicitly as a variable with escapes (assuming Windows)
path = "C:\\Users\\parsa\\Desktop\\kholase\\"

# Check if path to the path exists and if not, create it
import os
if not os.path.exists(path):
    os.makedirs(path)

# Define the function
def curve(lisst , m):
    for i in lisst:
        if i in m.columns:
            # Create figure and axis separately
            fig, ax = plt.subplots()
            # Set title
            plt.title(i) # `fig.suptitle(i)` works too
            # Plot on the axis
            ax.plot(m.Time , m[i])

            # Concatenate path with f-string filename and save figure
            fig.savefig(path   f"image{i}.png", format="png")

# Call the function to produce the plots
curve(lisst, m)

Instead of fig.savefig just plt.savefig should work the same here.

Hope this helps.

  • Related