Skip to content Skip to sidebar Skip to footer

How Do I Use The `_backend` Attribute Of A Sympy `plot`

In the following example I use Sympy to make a plot: from sympy import symbols, plot x = symbols('x') p = plot(x*x, x**3, (x, -2, 2), show=False) for n, line in enumerate(p, 2):

Solution 1:

Quick answer:

Use p._backend.fig.savefig('plot_with_legend_OK.png') instead of p.save('..').

This uses the savefig command from matplotlib as far as I know (if you want to know other options you can use).


The long(er) story of why it doesn't work. We can look at the code for self.save(path) which is called when you do p.save('plot_with_legend_OK_maybe.png').

    def save(self, path):
    if hasattr(self, '_backend'):
        self._backend.close()
    self._backend = self.backend(self)
    self._backend.save(path)

As you can see, if a _backend is established it will be closed, a new backend will be called and then it will save the figure using this backend. This will effectively undo all changes you did to the backend before then. That is why you cannot use the sympy show() and save() commands on plots that you have altered using the matplotlib backend.

The reason for this is simplicity, as given by the developers of sympy here:

Simplicity of code takes much greater importance than performance. Don't use it if you care at all about performance. A new backend instance is initialized every time you call show() and the old one is left to the garbage collector.

which also goes for save().


Post a Comment for "How Do I Use The `_backend` Attribute Of A Sympy `plot`"