plt.savefig doesn't overwrite existing file

Viewed 939

I have a loop which runs through a set of "program' names, creating a plot and placing it on a worksheet with xlsxwriter for each one. In order to do so, it temporarily saves the plot locally as 'chart.png'

plt.savefig('chart{}.png'.format(program))
plt.close()
ws.insert_image(r,2,'chart{}.png'.format(program),{'x_scale': 0.5, 'y_scale': 0.5})

This works just fine, but it creates a separate file for every program, of which I have more than fifty. I would like to simply create a 'chart.png' file, place it, and overwrite the file for the next chart, etc. However, this code:

plt.savefig('chart.png')
plt.close()
ws.insert_image(r,2,'chart.png',{'x_scale': 0.5, 'y_scale': 0.5})

puts an identical chart on every sheet. It looks like chart.png isn't getting overwritten with each new save, even though the previous code showed that matplotlib is creating a new chart for each program. Thanks for any assistance on this.

1 Answers

worksheet.insert_image() does not store the image into the XLSX file directly (Python source). Instead, it only records the information like cell, image filename, offset, scale, etc. in a list.

Only on workbook.close(), the XLSX and the accompanying images get stored to disk. Therefore, you should only see the last version of the image repeated in the file.

The easiest way would be to live with the fact that you have multiple temporary image files needed before the XLSX gets written. You can store them in a temporary directory, keep track of the filenames and delete these files after the workbook is written to disk.

Related