Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib Savefig will NOT overwrite old files

This seems like it must be a permissions issue on my machine. After a systems update on Windows 10, when I run:

import matplotlib.pyplot as plt
#make figure
plt.plot([1,2,3,4])
plt.ylabel('some numbers')

#save
plt.savefig("./figs/my_plot.jpg")

It will create the figure the first time the code is run. If I make a change to the code (e.g. change label) and then re-run, the plot shown in a Jupyter Notebook is updated, but the file saved on my machine is not! This is a new issues as of today, after a systems update was pushed out, so this seems like a likely culprit. Any insight for me to fix this issue, besides creating a new file name every time a change is made?

like image 407
EHB Avatar asked Feb 28 '18 22:02

EHB


People also ask

Will Savefig overwrite?

As Date Created doesn't change when matplotlib . savefig overwrites a file the Date column never changes.

What is the correct way of importing matplotlib library?

In the command line, check for matplotlib by running the following command: python -c "import matplotlib"


2 Answers

TLDR: The photos WERE being overwritten, but the date was kept the same as the original file, due to a quirk of windows when a folder has lots of photos.

Jon's answer from 10/2/2015 did the trick for me. https://superuser.com/questions/147525/what-is-the-date-column-in-windows-7-explorer-it-matches-no-date-column-from/335901#335901

Basically windows detects lots of pictures in a folder and "optimizes" said folder for pictures. This means the column displayed is Date rather than Date Modified as it would be for a folder "optimized" for documents. Date takes the earlier of Date Created and Date Modified. As Date Created doesn't change when matplotlib .savefig overwrites a file the Date column never changes.

To resolve this issue I customized the folder for documents. To do this select the folder and open the properties window. Navigate to the customize tab then select documents under "optimize this folder for."

like image 197
bbade Avatar answered Oct 11 '22 07:10

bbade


It may be simple and stupid, but I will just do the following:

import os
import matplotlib.pyplot as plt
#make figure
plt.plot([1,2,3,4])
plt.ylabel('some numbers')

#save
strFile = "./figs/my_plot.jpg"
if os.path.isfile(strFile):
   os.remove(strFile)   # Opt.: os.system("rm "+strFile)
plt.savefig(strFile)

It may be quite hard to use directly "rm" as system command line, but you can use any other option similar to that one.

But being honest it's strange that matplotlib does not overwrite the file.

EDIT

I see that you are using windows, so you may use "del" as delete command line instead of "rm" for unix.

like image 14
iblasi Avatar answered Oct 11 '22 05:10

iblasi