Plotting Functions With Sympy
3 min readMar 19, 2021
import matplotlib.pyplot as plt
from sympy import tan, exp, plot, symbols, log, latex
This is a function for plotting mathmetical functions
In [2]:
def plot_functions(f,
g = None,
show = False,
diff_plot = False,
xlim = (-10, 10),
ylim = (-10, 10),
color = ['r', 'm', 'b', 'g']): x = symbols('x')
if g is None:
p1 = plot(f(x), (x, xlim[0], xlim[1]),
show = False,
line_color = color[0],
ylim = ylim,
label = f'${latex(f(x))}$',
legend = True) if diff_plot:
p2 = plot(f(x).diff(), (x, xlim[0], xlim[1]),
show = False,
line_color = color[1],
ylim = ylim,
label = f'${latex(f(x).diff()}$',
legend = True)
p1.extend(p2) if show:
p1.show()
return p1p1 = plot(f(x), (x, xlim[0], xlim[1]),
show = False,
line_color = color[0],
ylim = ylim,
label = f'${latex(f(x))}$',
legend = True)
p2 = plot(g(x), (x, xlim[0], xlim[1]),
show = False,
line_color = color[1],
ylim = ylim,
label = f'${latex(g(x))}$',
legend = True)
p1.extend(p2)
if diff_plot:
p1_diff = plot(f(x).diff(), (x, xlim[0], xlim[1]),
show = False,
line_color = color[2],
ylim = ylim,
label = f'${latex(f(x).diff()}$',
legend = True)
p1.extend(p1_diff) p2_diff = plot(g(x).diff(), (x, xlim[0], xlim[1]),
show = False,
line_color = color[3],
ylim = ylim,
label = f'${latex(g(x).diff()}$',
legend = True)
p1.extend(p2_diff)
if show:
p1.show()
return p1
Creating a symbol x
In [3]:
x = symbols('x')
Now, we can plot any function.
In this we are plotting the tan function
In [4]:
f = lambda x: tan(x)
plot_functions(f, show = True)
Plotting the Log function with its derivative.
In [5]:
f = lambda x: log(x)
plot_functions(f, show = True, diff_plot = True
Comparing two functions, log and exp. (with its derivative)
In [6]:
f = lambda x: log(x)
g = lambda x: exp(x)
plot_functions(f, g, show = True, diff_plot = True)
Which function has more rate of change, x ** 2 or 2 ** x?
In [7]:
f = lambda x: x**2
g = lambda x: 2**x
plot_functions(f, g, ylim = [0, 1000], show = True)
As you can see the function 2 ** x has very high rate of change.
In [8]:
f = lambda x: x**2
g = lambda x: 2**x
plot_functions(f, g, ylim = [0, 1000], diff_plot = True, show = True)