无法在Windows上保存matplotlib图形

时间:2019-03-17 10:40:30

标签: python python-3.x matplotlib

我目前在Windows(10)上保存matplotlib图形时遇到一些困难。我知道需要使用原始字符串,但是即使使用原始字符串并确保路径正确,也会引发FileNotFoundError。我也尝试过使用os.path.normpath,但这也很顺利。相关行如下:

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"))

和错误:

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'

尝试通过plt.show()保存图形还返回“没有这样的文件或目录”错误。

非常感谢您的帮助!

马特

更新:该代码在保存在辅助硬盘驱动器(例如d:\)上但不在c:\上时有效。我怀疑有权限错误,但是即使在命令提示符下授予管理员权限,问题仍然存在。

更新2 :我终于弄清楚了原因。在Fall Creators Update中出现的新“受控文件夹访问”功能似乎是问题的根源,然后可以通过解除阻止受保护的文件夹来轻松解决此问题。

0 个答案:

没有答案