Trouble saving a matplotlib figure on Windows

344 views Asked by At

I'm currently experiencing some difficulties saving a matplotlib figure on Windows (10). I'm aware that raw strings need to be used, but even using those and making sure that the path is correct, a FileNotFoundError gets raised. I've also tried with os.path.normpath but this has been uneventful as well. Here are the relevant lines:

fig, ax = plt.subplots()
ax.plot(sin_i, sin_r, label='acrylic glass')
ax.plot(sin_i, sin_r_wtr, label='water')

ax.legend()

ax.set(xlabel=r'$sin(\alpha_{refracted})$', ylabel=r'$sin(\alpha_{incident})$',
       title=r'$f([sin(\alpha_{refracted}])$ for acrylic glass and water')

ax.grid()

#fig.savefig(r"c:\Users\julie\Pictures\PY3graph.png")
fig.savefig(os.path.normpath("c:/Users/julie/Pictures/PY3graph.png"))

and the error:

Traceback (most recent call last):
  File "PY_3_graphs.py", line 31, in <module>
    fig.savefig(r"PY_3_graph.png")
  File "C:\Users\julie\AppData\Local\Programs\Python\Python37-32\lib\site-packages\matplotlib\figure.py", line 2094, in savefig
    self.canvas.print_figure(fname, **kwargs)
  File "C:\Users\julie\AppData\Local\Programs\Python\Python37-32\lib\site-packages\matplotlib\backend_bases.py", line 2075, in print_figure
    **kwargs)
  File "C:\Users\julie\AppData\Local\Programs\Python\Python37-32\lib\site-packages\matplotlib\backends\backend_agg.py", line 521, in print_png
    cbook.open_file_cm(filename_or_obj, "wb") as fh:
  File "C:\Users\julie\AppData\Local\Programs\Python\Python37-32\lib\contextlib.py", line 112, in __enter__
    return next(self.gen)
  File "C:\Users\julie\AppData\Local\Programs\Python\Python37-32\lib\site-packages\matplotlib\cbook\__init__.py", line 407, in open_file_cm
    fh, opened = to_filehandle(path_or_file, mode, True, encoding)
  File "C:\Users\julie\AppData\Local\Programs\Python\Python37-32\lib\site-packages\matplotlib\cbook\__init__.py", line 392, in to_filehandle
    fh = open(fname, flag, encoding=encoding)
FileNotFoundError: [Errno 2] No such file or directory: 'c:\\Users\\julie\\Pictures\\PY3graph.png'

Trying to save the figure via plt.show() also returns a 'No such file or directory' error.

I'd be very thankful for your help!

Matts

Update: The code works when saving on a secondary hard drive (eg. d:\ ) though not on c:\ . I suspected a permission error, but the problem remains even when giving admistator permission to the command prompt.

Update 2: I finally figured out what the cause was. The new 'Controlled Folder Access' feature that made its appearance with the Fall Creators Update seems to be at the root of the problem, which can then be easily solved by unblocking the protected folders.

0

There are 0 answers