15

This code

from sympy import *
x=Symbol('x')
p1 = plot(x**2,(x,-2,2))
p2 = plot(x**3,(x,-2,2))

results in two separate plots.

Instead of two separate plots, I want to display them with matplotlib as subplots:

import matplotlib.pyplot as plt
fig = plt.figure()
ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)
plt.show()

How can I add p1 and p2, so that they are displayed as subplots inside the matplotlib figure?

M. Heuer
  • 395
  • 3
  • 13
  • 1
    I might be wrong. But sympy's plot does not seem to take ```ax``` arguments and everything seems figure-based. I think the state of matplotlib still is: merging multiple figures is hacky at least, not recommended. (For this example it also makes not much sense to me to not use mpl directly; but maybe it will be different for your real task). – sascha Oct 18 '17 at 13:39

3 Answers3

18

The problem is that sympy Plot creates its own figure and axes. It is not meant to draw to an existing axes.

You may however replace the axes the plot is drawn to by an existing axes prior to showing the sympy plot.

from sympy import Symbol,plot
import matplotlib.pyplot as plt

def move_sympyplot_to_axes(p, ax):
    backend = p.backend(p)
    backend.ax = ax
    backend.process_series()
    backend.ax.spines['right'].set_color('none')
    backend.ax.spines['bottom'].set_position('zero')
    backend.ax.spines['top'].set_color('none')
    plt.close(backend.fig)


x=Symbol('x')
p1 = plot(x**2,(x,-2,2), show=False)
p2 = plot(x**3,(x,-2,2), show=False)


fig, (ax,ax2) = plt.subplots(ncols=2)
move_sympyplot_to_axes(p1, ax)
move_sympyplot_to_axes(p2, ax2)

plt.show()

enter image description here

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
  • That's something i need to remember for the future. I already checked out those backend-attributes, but was not able to use them. What is your definition of *hacky* here though? Non-nice code or fear about upcoming matplotlib changes? – sascha Oct 18 '17 at 15:35
  • 1
    @sascha No this is fine from the matplotlib side. By hacky I mean that there isn't really any API to use. The solution first prevents the sympy "backend" to plot anything, then artificially replaces one of its attributes, then manually calls part of what its `show` method would do. So, it's hacky in the way that monkey patching would be hacky as well. – ImportanceOfBeingErnest Oct 18 '17 at 16:39
  • 6
    This seems to be broken on Sympy 1.5, at least for me. I had to replace `backend.process_series()` with the following: `backend._process_series(backend.parent._series, ax, backend.parent)` – Sébastien Loisel Feb 16 '20 at 14:55
7

My solution does not add p1, p2 to the subplots directly. But (x,y) coordinates from them are captured and used instead.

import matplotlib.pyplot as plt
from sympy import symbols
import numpy as np

from sympy import symbols
from sympy.plotting import plot

# part 1
# uses symbolic plot of functions
x = symbols('x')

#p1, p2 = plot(x**2, x**3, (x, -2, 2))

# this plot will not show ...
# only produce 2 curves
p1, p2 = plot((x**2, (x, -2, 2)), \
                (x**3, (x, -2, 2)), \
                show=False)

# collect (x,y)'s of the unseen curves 
x1y1 = p1.get_points()  # array of 2D
x2y2 = p2.get_points() 

# part 2
# uses regular matplotlib to plot the data

fig = plt.figure(figsize=(8, 5))
ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)

# do subplot 1 
ax1.plot(x1y1[0], x1y1[1], 'g')  # plot x**2 in green
ax1.set_xlim([-2, 2])
ax1.set_xlabel('X1')
ax1.set_ylabel('Y1')
ax1.set_title('Line1')  # destroyed by another .title(); axis metho1

# do subplot 2
ax2.plot(x2y2[0], x2y2[1], 'r')  # plot x**3 in red
ax2.set_xlim([-2, 2])
ax2.set_xlabel('X2')
ax2.set_ylabel('Y2')
ax2.set_title('Line2')

fig.subplots_adjust(wspace=0.4) # set space between subplots

plt.show()

The resulting plot:

output

swatchai
  • 17,400
  • 3
  • 39
  • 58
2

You can simply use a plotgrid to get 2 or more plots in one figure.
See also: sympy.plotting.PlotGrid()

Here's a working example:

import sympy as sp
from matplotlib import pyplot as plt

# define functions
x = symbols('x')
f = sin(x)
g = cos(x)

# create separate plots
p1 = plot(f, show=False, xlim=(-pi, pi), line_color='blue', legend=True)
p2 = plot(g, show=False, xlim=(-pi, pi), line_color='red', legend=True)

# create a plotgrid with 2 rows and 1 column
plotgrid = sp.plotting.PlotGrid(2, 1, p1, p2, show=False, size=(5., 3.5))
plotgrid.show()

Resulting plot:

subplots in sympy by using plotgrid

Sander van den Oord
  • 10,986
  • 5
  • 51
  • 96