Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change default filename from Matplotlib NavigationToolbar in a PyQt5 application?

I am writing an application in Python 3.5 & PyQT 5. In this application I have an embedded matplotlib canvas and an embedded matplotlib NavigationToolbar. The application measures some data and then plots them. The user at some point wants to export the plot and save it into a ".png" file somewhere and then measure something new.

For this, I have been using the "floppy"/"save" icon on the NavigationToolbar and it works well. However, when I click it, it opens a dialog at the root folder of the program (or last opened folder) and pre-fills the name of the saved image as "image.png".

I would like to change this pre-filled default name to something custom to my program, such as "measurement_7453243.png" or "2017_01_16_measurement.png". Is there a way that would allow me to do this?

Idea #1: What I found is the option to use matplotlib.rcParams['savefig.directory'] and use that to set the directory of where the dialog should be opened - not the filename though. I cannot seem to find a 'savefig.XXXX' property that would change the default filename.

Idea #2: I could make a custom button in my app outside of the NavigationToolbar, which would run a custom file saving dialog with Qt and then use savefig() to save the figure. But why do that if there is already a nice button that does ALMOST what I want?

Any tips and ideas, as well as "this cannot be done" with proper sources will be greatly appreciated.

like image 429
erthy Avatar asked Oct 24 '25 03:10

erthy


1 Answers

Not sure if you can always do this, but in my case the figure instance had a canvas attribute which I could monkeypatch as Goyo suggested.

import matplotlib.pyplot as plt
f = plt.figure()
c = f.canvas
my_adventurous_filename = 'figure-III' # irony
c.get_default_filename = lambda : '%s.%s' % (my_adventurous_filename,
                                             c.get_default_filetype())
plt.show()
like image 141
Andreas Grivas Avatar answered Oct 26 '25 16:10

Andreas Grivas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!