3

A similar question was asked here and here on Stack, but I'm not satisfied as it still did not resolve my issue.

Consider I have a function which does some calculations and displays a figure (without returning a figure object). Out of personal preference (and to keep track of what my plots looked like without saving each) I use %matplotlib inline in IPython. Now after I generated some plots I decide to save one of them (say the second out of 3 displayed in the notebook), which works fine by right clicking and choosing 'Save as...', but only as .png.

Is there a way to save it as .pdf without modifying the function to return a figure object? (I know it is not difficult at all, but for most of my cases it is just unnecessary since it is 1 out of, say, 20 figures worth saving in the end).

I figured out that the backend is being changed after %matplotlib inline which is (I guess) the reason why I can not save figures as .pdf. The workaround seems to be using %config InlineBackend.close_figures = False and using plt.savefig(...)(answer from here). But this way I could save only the last figure and have to close the figures manually each time.

If my problem arises from bad program workflow / programming style, I will happily accept suggestions on how to do it better. If a code example is needed, I can provide one. I use:

ipython (2.1.0)
matplotlib (1.4.1) (with Qt4Agg backend if not inline)
Python 2.7.6
MacOSX 10.9.4
Community
  • 1
  • 1
olga.bio
  • 281
  • 3
  • 15
  • 1
    In short, no, there isn't a way to do what you want. The notebook interface in your browser is not aware that that image is connected to a particular matplotlib figure object, so it can only offer you the png to save. There's a config switch to make it display using SVG instead, but not PDF. – Thomas K Oct 22 '14 at 22:39
  • I wasn't aware of this option, thank you! That is actually sufficient for me (I'm using Latex for writing, which is fine with .svg as well). If you post this as an answer instead of a comment, I can accept it ~ – olga.bio Oct 24 '14 at 10:03

1 Answers1

2

Reposting as an answer:

You can't save the PDF directly from your browser, because the browser and JS code doesn't know that the PNG image it displays is associated with a particular matplotlib figure - indeed, it doesn't know about matplotlib at all. All that is handled by the Python kernel process running your code.

However, you can configure IPython to display figures in SVG format, as described in the docs. It also appears to have a PDF option, though I forget what that does.

Thomas K
  • 39,200
  • 7
  • 84
  • 86