Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python mathplotlib savefig FileNotFoundError

I've made a figure using matplotlib and now I'm trying to save it to file using matplotlib.pyplot.savefig

import matplotlib.pyplot as plt

# . . .

plt.savefig("/home/username/PycharmProjects/sandbox/images/result.png")

Directory "/home/username/PycharmProjects/sandbox/images/" exists, but unfortunately it occurs FileNotFoundError at plt.savefig call.

Does anybody know, how can this problem be solved?

like image 398
Artem Avatar asked May 24 '26 23:05

Artem


2 Answers

Most errors related to saving files and plots can be prevented by

  • plotting the graph,
  • building the path to the save directory without hard coding it into a string,
  • saving the plot.

Independent of your operating system, you can get the current directory your python script is running and from there, you can save your file in that directory or create a subfolder in this location to save your file in. Both implementations are described below using the os library.

Import required libraries

import os
import matplotlib.pyplot as plt

Plot the graph

X = [_ for _ in range(100)]
plt.plot(X)
plt.title('A plot of 1st 100 numbers')

Get current working directory path

current_directory_path = os.getcwd()
file_name = 'result.png'

This gets the path to the current directory's path you are running the python script from. No need to hard code the path yourself which could result in errors in most cases if you forgot to escape special characters or appropriate slashes for your OS.

Build file_path to save in the current working directory

file_path = os.path.join(current_directory_path, file_name)

In windows, you get something like c:\\Users\\...\\result.png. This may differ in linux.

Build file_path to save plot in a subfolder

subfolder_path = os.path.join(current_directory_path, 'subfolder')

if not os.path.exists(subfolder_path):
    os.makedirs(subfolder_path)

file_path = os.path.join(subfolder_path, file_name)

The above checks if 'subfolder' directory exists in the current directory if not, creates it. In windows, you get something like c:\\Users\\...\\subfolder\\result.png'

Save the plot

plt.savefig(file_path)

Finally, file is saved to the specified file_path with no errors.

like image 98
Prosper Ablordeppey Avatar answered May 27 '26 13:05

Prosper Ablordeppey


In my case, the problem was the leading /. So the following should work:

plt.savefig("home/username/PycharmProjects/sandbox/images/result.png")
like image 25
mneumann Avatar answered May 27 '26 13:05

mneumann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!