Skip to content

Avoid potentially changing the matplotlib backend when scraping#1102

Merged
larsoner merged 1 commit intosphinx-gallery:masterfrom
ayshih:backend
Mar 15, 2023
Merged

Avoid potentially changing the matplotlib backend when scraping#1102
larsoner merged 1 commit intosphinx-gallery:masterfrom
ayshih:backend

Conversation

@ayshih
Copy link
Copy Markdown
Contributor

@ayshih ayshih commented Mar 15, 2023

The matplotlib backend is set to agg in the function _import_matplotlib(), which is called both (1) when resetting matplotlib for each example and (2) when scraping each code block for matplotlib plots (matplotlib_scraper()). The forcing of the backend to agg in the latter case means that an example is unable to make use of non-agg backends.

My particular use case is that I want to use mplcairo in an example to show how to use its blending operators, e.g., the example begins:

import matplotlib
matplotlib.use("module://mplcairo.base")
...

With the current code, the matplotlib backend is immediately set back to agg after scraping the first code block, and so the subsequent code blocks (and the eventual plot) do not work properly.

This PR replaces the call of _import_matplotlib() in matplotlib_scraper() with direct imports of matplotlib and matplotlib.pyplot, so the backend will not be set to agg when scraping for matplotlib plots. Recall that the backend will still continue to be set to agg when resetting matplotlib between examples. So, the result of this PR is that an explicit call to change the backend within an example will now persist through the rest of that example, but otherwise the backend will be agg.

@larsoner
Copy link
Copy Markdown
Contributor

Recall that the backend will still continue to be set to agg when resetting matplotlib between examples. So, the result of this PR is that an explicit call to change the backend within an example will now persist through the rest of that example, but otherwise the backend will be agg.

Thanks for the deep investigation and fix, I agree this makes sense! I think a regression test here would be hard so I'm not going to ask for it... but if you see an easy way to add one feel free in a follow-up PR :) Thanks @ayshih !

@larsoner larsoner added the bug label Mar 15, 2023
@larsoner larsoner merged commit 1cd32df into sphinx-gallery:master Mar 15, 2023
@ayshih
Copy link
Copy Markdown
Contributor Author

ayshih commented Mar 15, 2023

Thanks for the quick merge! I do have an idea that might work for a regression test that I'll try soon. If it works, I'll PR it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants