简体   繁体   中英

Problem with matplotlib savefig function in PyCharm

I am new in using Python and I'm using PyCharm as the working environment. I am having problems using the savefig function inside a double for-loop with the following code:

for i in range(len(Name1)):
    for j in range(len(Name2)):
        fig2 = plt.figure()
        plt.scatter(Data.loc[:, Name2[j]], Data.loc[:, Name1[i]], s=1.5)
        plt.xlabel( Name2[j])
        plt.ylabel(Labels[i] + Units[i] )
        plt.savefig('Figures/' + KPI[i] + variations[j] +'.pdf', bbox_inches="tight")
        fig2.show()

where Name1 and Name2 are just lists of different filenames.

The error I get is the following:

    Traceback (most recent call last):
  File "<input>", line 8, in <module>
  File "C:\Projects\test\testvenv\lib\site-packages\matplotlib\pyplot.py", line 729, in savefig
    res = fig.savefig(*args, **kwargs)
  File "C:\Projects\test\testvenv\lib\site-packages\matplotlib\figure.py", line 2180, in savefig
    self.canvas.print_figure(fname, **kwargs)
  File "C:\Projects\test\testvenv\lib\site-packages\matplotlib\backend_bases.py", line 2091, in print_figure
    **kwargs)
  File "C:\Projects\test\testvenv\lib\site-packages\matplotlib\backends\backend_pdf.py", line 2496, in print_pdf
    file = PdfFile(filename, metadata=metadata)
  File "C:\Projects\test\testvenv\lib\site-packages\matplotlib\backends\backend_pdf.py", line 432, in __init__
    fh, opened = cbook.to_filehandle(filename, "wb", return_opened=True)
  File "C:\Projects\test\testvenv\lib\site-packages\matplotlib\cbook\__init__.py", line 432, in to_filehandle
    fh = open(fname, flag, encoding=encoding)
FileNotFoundError: [Errno 2] No such file or directory: 'Figures/corr_eff_enmp.pdf'

Thanks in advance :)

It seems like you are not using the full path to the /Figures folder. If the Figures folder is not nested inside where your python files are, then this is the root of the error. I would use the full path to said folder. Linked bellow are ways to find the full path to your folder for both Windows and Mac https://www.laptopmag.com/articles/show-full-folder-path-file-explorer . https://osxdaily.com/2013/06/19/copy-file-folder-path-mac-os-x/ .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM