Avoiding Pitfalls in Plotting with Python’s sympy

Photo by Ricardo Gomez Angel on Unsplash

This is a quick article on simple plotting in Python’s computer algebra system sympy because this is quite convenient in Jupyter notebooks when working with sympy . More complex plotting is usually done in matplotlib , but this usually takes more time.

The one thing that I struggled with in plotting with sympy in the beginning is: how do I control the plotting options for the different curves if you have more than one curve in a single plot? That’s what this post is about. The philosophy of doing is is a bit similar to Mathematica and looks a bit weird when you come from a different environment. But anyways, it’s quite convenient, so here it is.

As usual, we start by importing and defining the symbols we need.

The simplest and quickest way to plot an expression as a curve is by simply calling the plot function and giving a range over which to plot. Here, we plot a parabola from -1 to 1 and a straight line from 0 to 1:

By default, the label of the vertical axis is 𝑓(𝑥), which may not be what you want. This can be easily changed:

You can only give global settings for a plot, like the ylabel option above which then applies to the whole plot. But what, if you want to change the line colors individually and not globally? And what if you want to set a legend for each curve? Well, create a plot for each curve and don't show it! For each plot, do the global settings and then merge the plots. For example:

There are a lot more that you can change, so look up the documentation to see what option you need. But the philosophy is always the same. Even if you use different plotting functions like plot_parametric for plotting parametrized curves. The recommendation is always: make a plot for the first curve, do all the global settings there, and don't show it. Then for each additional curve make an additional plot with the specific settings and also show=False . Then add all the additional plots to the base plot by calling the append method (or extend ). And in the end, call show on the base plot.