Problem
When saving a matplotlib figure using fig.savefig(), the figure looks different from when the figure is rendered in a Jupyter Notebook.
Question
How can I render a static (non-interactive) figure in the Jupyter Notebook, such that it looks exactly like what I would see when saving the figure using `fig.savefig('example.pdf')?
Context
When I make a figure using matplotlib, I carefully adjust the size and spacing of everything, and then save it using fig.savefig('example.pdf') without any uncontrolled adjustments (i.e. pad_inches=0 and bbox_inches='tight'). This ensures that all elements, in particular text, are the correct size. A simple example is something like:
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(1,1))
ax.plot(WHATEVER)
# Do some fine adjustments as needed
fig.subplots_adjust(left=0.15, right=0.8, bottom=0.1, top=0.95, wspace=0.1, hspace=0.1)
fig.savefig('my_fig.pdf')
In order to quickly iterate adjusting my figures, I would like to be able to run a script (or #%% cell in a .py script) and immediately see the new figure within the IDE using plt.show(), rather than always saving using fig.savefig(...), which can take a little while and requires closing and re-opening the resulting pdf to see the changes. The obvious choice is to use the Jupyter Notebook. However, when a figure is rendered in the notebook, it appears quite different from when it is saved. In particular, the edges of the canvas are not the same in both cases.
Clearly, this has to do with the backend used for rendering. When saving the figure as a .pdf, the pdf backend is used. In contrast, in the notebook, the inline backend is used.
Previously, I have used the SciView feature in PyCharm. This renders and displays the figure when plt.show() is called as a png. I am not sure which matplotlib backend it uses, but the output looks identical to what is saved using fig.savefig.
Previous questions
Several previous questions talk about the discrepancy between the output obtained when using plt.show() and plt.savefig(). However, they mostly address changing the output of plt.savefig() to match what is seen with plt.show(), rather than the other way around.
Differences between figure saved and figure displayed
Why is matplotlib displaying the plot differently in the jupyter notebook than when exported to pdf
plt.show()has, have you seen here?