A light blue single line wave on a dark blue background.
Image by Shahanaz Akter on pixabay

Beginner’s Guide to Plotting in Python

SymPy and matplotlib

M.Hamxa
7 min readJun 29, 2023

--

Python is widely recognized as a go-to programming language among physicists for its capabilities in data visualization and mathematical programming.

Plotting in Python may seem intimidating at first, but once you become familiar with it, you’ll find that it’s actually quite straightforward. It’s just a matter of getting some practice and gaining confidence.

In this guide, we will focus on two specific libraries: Matplotlib and SymPy.

By the end of this guide, you will know how to create basic plots.

  1. Points and lines
  2. Scatter plot
  3. Polynomials
  4. Multiple plots on same axis
  5. Transcendental functions
  6. Subplots
  7. Plotting in SymPy
  8. Multiple plots on same axis (SymPy)
  9. 3D plots
  10. A Special Case
  11. Piecewise functions
  12. Surprise!

Installing Relevant Libraries:

I use Jupytar Notebook. It can be accessed from Anaconda, which in turn can be downloaded from https://www.anaconda.com/download.

After Opening Jupyter Notebook, you will see New on the top extreme right. Click.

The interface would look something like this.

interface of Jupyter notebook

Now, copy paste this into the first cell and press Ctrl+Enter. This will download relevant libraries.

import sympy as sym
import matplotlib.pyplot as plt
import numpy as np
from IPython.display import display,Math

Press the ‘+’ button on the toolbar to go to new cell. Now we are ready for some action.

1. Points and lines:


plt.plot([-1,3],[-3,9])

#points are in form (x,y)

plt.plot(-1,-3,'r*')
plt.plot(3,9,'ro')
plt.axis([-4,5,-5,10])
plt.plot()

#Then press Ctrl+Enter to show the plot.

[-1,3] refers to the domain of a line and [-3,9]refers to the range of line.

plt.axis([a,b,c,d]) is for the x and y-axis limits of the plot respectively.

A number of markers can be used to show the points. Some are:

‘.’: Point marker ‘o’ : Circle marker ‘s’: Square marker ‘p’: Pentagon marker ‘*’: Star marker

r is used for the Red color.

The plot looks like this.

2. Scatter Plots :

x=[3.2,4.54,5.334,6]
y=[5,4,8.34,2.444]
plt.scatter(x,y)
plt.xlabel('x')
plt.ylabel('y')
plt.show()

Scatter plots are an effective tool for correlation analysis, allowing us to determine whether data sets exhibit any relationship.

3. Polynomials:

x=np.linspace(-4,4,100) # values that need to be substitued in function
y=x**2+x**(3) # function
plt.plot(x,y,label= '$x^2+x^3$',linewidth=2, \
linestyle='--',color='b') # or color=(R,G,B).. (0,0,1)
# dollar sign at start and end for latex format.

# for linestyle you can also use
#'-','--', ':'

plt.legend()
plt.ylim([-20,20])
plt.xlim([-10,10])
#or plt.axis([-10,10,-20,20])
plt.xlabel('x')
plt.ylabel('y')
plt.grid(True)
plt.show()

np.linspace(-4, 4, 100) generates an array with 100 values between -4 and 4, including both endpoints. These values are substituted in ‘y’ and a plot is generated.

Thankfully, all this happens behind the scene. You only get to see a nice plot.

Now, for color coding,

‘b’: blue ‘g’: green ‘r’: red ‘c’: cyan ‘m’: magenta ‘y’: yellow ‘k’: black ‘w’: white.

RGB color coding can also be employed by adjusting the numbers within the (R, G, B) format.(1,1,0) would give you yellow; (1,0,0) would give you red. You can also get a mixture of colors by using values like (0.5,0.6,0.3).

The plot for the above code is

4. Multiple plots on the same axis:

x=np.linspace(-4,4,100) 
y=x**2+x**(3) #function
g=1/x #function
plt.plot(x,y,label= '$x^2+x^3$',linewidth=2, \
linestyle='--',color='b')
plt.plot(x,g,label='$1/x$',color='r')

plt.legend()
plt.ylim([-20,20])
plt.xlim([-10,10])
plt.xlabel('x')
plt.ylabel('y')
plt.grid(True)
plt.show() # all plots before before plt.show() will be shown on same
#plot

5. Transcendental Functions:

x=np.linspace(-4,4,200)
y=np.cos(x**2)+x**2
plt.plot(x,y,label='f')
plt.legend()

For cos(x), sin(x), tan(x), log and exponential constant (e) use ‘ np. ’; they are a part of the NumPy library.

6. Subplots:

x=sym.symbols('x')
xx=sym.symbols('xx')
x=np.linspace(-4,4,200)
xx=np.linspace(-10,10,200) # domain for 2nd (g) function.

f=np.cos(x**2)+x #functions
g=np.exp(xx) #functions

fig, axs = plt.subplots(1, 2, figsize=(8, 6))
#1 row and 2 columns

# for f plot
axs[0].plot(x,f,label='f')
axs[0].set_xlabel('x')
axs[0].set_ylabel('f')
axs[0].legend()

# for g plot
axs[1].plot(x,g,label='g',color='r')
axs[1].set_xlabel('x')
axs[1].set_ylabel('g')
axs[1].legend()

plt.show()
fig, axs = plt.subplots(1, 2, figsize=(8, 6))

This function call creates a grid of subplots. The 1 represents the number of rows, and the 2 represents the number of columns.

figsize=(8, 6): This parameter sets the size of the figure in inches. You can adjust these values to suit your needs.

7. Plotting in SymPy:

SymPy has its own plotting module too. But it does not provide as much freedom as matplot lib does. Providing the domain of x is optional.

x=sym.symbols('x')
y=sym.cos(x)*x**3
p=sym.plotting.plot(y,(x,-7.5,7.5),xlabel='x',ylabel='y',\
title='plot', legend=True, line_color='red')
#(x,-7.5,7.5) is the domain

sym.symbols('x') is necessary. It is used to declare that ‘x’ will be used as an algebraic variable.

Here too, sym. is necessary before cos(x), sin(x), tan(x), cot(x), log and exponential constant (e).

8.Multiple plots on the same axis (SymPy):

x=sym.symbols('x')
y=sym.cos(x)*x**2
g=sym.exp(x)
p=sym.plotting.plot(y,(x,-7.5,7.5),xlabel='x',ylabel='y',\
legend=True, line_color='red', show=False)
# (x,-7.5,7.5) is the domain: x values from -7.5 to 7.5
p.extend(sym.plotting.plot(g,(x,-7.5,7.5),show=False))
p.title='Functions'
p.ylim = [-20,100] #y axis limit
p.xlim = [-10,10] #x axis limits
p.show()

p.extend() is used to plot the graph on same axis. I have used the variable p, any other word or letter could also be used.

show=False tells Python not to plot now. Instead, plot on the same axis when p.show() is called.

9. 3D plots:

x,y=sym.symbols('x,y')
f=x**2+y #function
#just add 3d after plot!
sym.plotting.plot3d(f,(x,-10,10),(y,-10,10))

Since a multivariable function produces a 3d plot, we will use ‘x’ and ‘y’ as independent variables.

To plot, just use sym.plotting.plot3d .

Also — if you choose the domain of x, you must choose the domain of y too.

10.A Special Case:

Several times we need to perform calculations on functions like finding their turning points — and also plot them. For that purpose, we use lambdify feature.

x=sym.symbols('x')
y=(x)*sym.exp(x)

#I am trying to find turning point here
derivative=sym.diff(y)
display(Math(sym.latex(derivative)))
sol=sym.solve(derivative)
print(sol)

#plotting part
yxx=sym.lambdify(x,y) # to make a function callable
xx=np.linspace(-5,5,50) #domain of the function
# easy way to remember: x is algebraic variable for algebraic
#manipulations. To plot a graph, we need another variable (xx) which
# can be assigned a domain.
plt.plot(xx,yxx(xx),label='%s' %(sym.latex(y)))
plt.ylim([-2,10])
plt.legend()
plt.grid(True)

yxx=sym.lambdify(x,y) is the key here. The sym.lambdify feature allows you to convert symbolic expressions into callable functions, typically for numerical evaluation.

Do not forget to write yxx(xx) in plt.plot(xx,yy(xx)) .

11.Piecewise functions

x=sym.symbols('x')
piece1 = x # for x<0
piece2 = sym.cos(x) # for x>0 and x<5
piece3 = 1/x # for x>=5

# put them together
y = sym.Piecewise( (piece1,x<0),(piece2,(x>=0) & (x<5)),(piece3,x>=5) )

# making another xx variable to give domain to the function

xx = np.linspace(-5,25,100)
fxx = sym.lambdify(x,y)

plt.plot(xx,fxx(xx),'b')
plt.xlabel('x')
plt.ylabel('f(x)')
plt.grid(True)
plt.show()

sym.piecewise() is used to join all the components.

Piecewise functions are plotted by ‘lambdifying’ the function so it can become callable.

12. A comic graph

To make a plot which feels straight out of comic book, use with plt.xkcd(): before any plt command and indent all the lines below.

The last one will look like this.

Additional Info:

  1. Parenthesis placement matters; a single omission can cause an error.
  2. To add text in graph, plt.text(a,b,'enter text', fontsize=12, color='red)1 where (a,b) are coordinates of text.
  3. In sym.Piecewise(), P must be capitalized. Otherwise, Python gives error — ‘SymPy has no attribute piecewise’.
  4. In sym.plotting.plot() you have to use line_color=for color, while in plt.plot()just color= .
  5. Entering %matplotlib notebook at the start of code block would make the plot more aesthetic.
  6. With practice, you’ll become familiar with the details and nuances, such as realizing that plt.show() is not always necessary.
  7. plt.savefig(name.image format) saves the image of the plot; it can be accessed from File>Open.

The codes I have uploaded are exact and working. You can experiment by changing the values and plotting them in your own notebook.

--

--

M.Hamxa
Technological Singularity

I write on a variety of topics, ranging from computations to science narratives.