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?
Most errors related to saving files and plots can be prevented by
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 os
import matplotlib.pyplot as plt
X = [_ for _ in range(100)]
plt.plot(X)
plt.title('A plot of 1st 100 numbers')
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.
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.
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'
plt.savefig(file_path)
Finally, file is saved to the specified file_path with no errors.
In my case, the problem was the leading /. So the following should work:
plt.savefig("home/username/PycharmProjects/sandbox/images/result.png")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With