Grid in sympy plotting

223 views
Skip to first unread message

Lee Smith

unread,
Jun 25, 2019, 8:59:52 PM6/25/19
to sympy
Greetings:

I want to display a grid in a sympy plot.

The sympy.doc page only discusses mesh grids.

On searching through Google, I found only one result that suggested using matplotlib.pyplot in addition to the sympy.plot(...) method.

This should be simple and I am surprised that it is not asked more.

Thanks in advance,
lee

Oscar Benjamin

unread,
Jun 26, 2019, 6:26:38 AM6/26/19
to sympy
Hi Lee,

SymPy's plotting module uses matplotlib so it is reasonable to use the
matplotlib API for adding a grid.

I just tried this and it works fine:

In [1]: plot(x**2)
Out[1]: <sympy.plotting.plot.Plot at 0x7efd2fab3128>

In [2]: from matplotlib.pyplot import grid

In [3]: grid()

Oscar
> --
> You received this message because you are subscribed to the Google Groups "sympy" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to sympy+un...@googlegroups.com.
> To post to this group, send email to sy...@googlegroups.com.
> Visit this group at https://groups.google.com/group/sympy.
> To view this discussion on the web visit https://groups.google.com/d/msgid/sympy/01a492c1-f8df-4810-b413-063f65ce4fa1%40googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.

Lee Smith

unread,
Jun 27, 2019, 2:24:40 PM6/27/19
to sy...@googlegroups.com
Thank you !

Actually I tried this and got TWO graphs.  One just the grid then the functions!
Suggestions?
Sympy_grid.PNG

Oscar Benjamin

unread,
Jun 27, 2019, 2:59:27 PM6/27/19
to sympy
I guess it depends what environment you use (I used ipython). Looks like you're using Jupyter and I'm not sure how to plotting works there.


Lee Smith

unread,
Jun 27, 2019, 3:33:31 PM6/27/19
to sy...@googlegroups.com
Yep.  Well I will continue to look into this.  Of course, if I just did everything in matplotlib ... no problemo CODE ON !

Aaron Meurer

unread,
Jun 27, 2019, 3:38:33 PM6/27/19
to sympy
If you want advanced plotting things in SymPy it's often easier to plot your function directly with matplotlib using something like

import numpy as np
import matplotlib.pyplot as plt
a = np.linspace(-10, 10, 1000) # Replace with your desired range and number of points
f = sympy.lambdify(x, expr)
plt.plot(a, f(a))
# Modify the matplotlib plot using matplotlib functions here

This is more or less what sympy.plot does internally. The key here is that lambdify() will convert a SymPy expression into a NumPy function which can be applied to a numpy linspace and used directly with matplotlib's plot.

Aaron Meurer


Reply all
Reply to author
Forward
0 new messages