Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[ENH]: save_figure returns image fullpath #27744

Closed
Zybulon opened this issue Feb 4, 2024 · 0 comments · Fixed by #27766
Closed

[ENH]: save_figure returns image fullpath #27744

Zybulon opened this issue Feb 4, 2024 · 0 comments · Fixed by #27766

Comments

@Zybulon
Copy link
Contributor

Zybulon commented Feb 4, 2024

Problem

Hello,

I am integrating Matplotlib with the QtBackend inside a tool of data analysis.
I would be interested if the function save_figure from the NavigationToolbar2QT class could return the fullpath of the saved image (the variable fname).
For now I have overloaded this function by adding the return parameter but it would much neater if it was made directly inside matplotlib. Plus, this could interest other people.

For consistency, maybe it would be best to do that for all backends.

What do you think ?

Proposed solution

The function would look like this :

    def save_figure(self, *args):
        filetypes = self.canvas.get_supported_filetypes_grouped()
        sorted_filetypes = sorted(filetypes.items())
        default_filetype = self.canvas.get_default_filetype()

        startpath = os.path.expanduser(mpl.rcParams['savefig.directory'])
        start = os.path.join(startpath, self.canvas.get_default_filename())
        filters = []
        selectedFilter = None
        for name, exts in sorted_filetypes:
            exts_list = " ".join(['*.%s' % ext for ext in exts])
            filter = f'{name} ({exts_list})'
            if default_filetype in exts:
                selectedFilter = filter
            filters.append(filter)
        filters = ';;'.join(filters)

        fname, filter = QtWidgets.QFileDialog.getSaveFileName(
            self.canvas.parent(), "Choose a filename to save to", start,
            filters, selectedFilter)
        if fname:
            # Save dir for next time, unless empty str (i.e., use cwd).
            if startpath != "":
                mpl.rcParams['savefig.directory'] = os.path.dirname(fname)
            try:
                self.canvas.figure.savefig(fname)
            except Exception as e:
                QtWidgets.QMessageBox.critical(
                    self, "Error saving file", str(e),
                    QtWidgets.QMessageBox.StandardButton.Ok,
                    QtWidgets.QMessageBox.StandardButton.NoButton)
        return fname
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant