s

Problem10



Write a program that displays a plot of the functions $x$, $x^2$ and $2^x$ in the range[0,4].


import matplotlib.pyplot as pl

import numpy as np

# steps of 0.1 to make the plots smoother.

x = np.arange(0.,4.,0.1)  


## first creating an empty figure
fig = pl.figure()

# writing mathematical equation with math text. 
# use raw strings(precede the quote with an 'r') 
pl.suptitle(r'Plotting the functions x, $x^2$ and $2^x$ \
in the range [0,4]', fontsize = 14)

#pl.plot(x, x,"b",x, x**2,"r", x, 2**x,"g")
pl.plot(x,x, label = r"$f(x)=x$")
pl.plot(x,x**2, label = r"$f(x)=x^2$")
pl.plot(x, 2**x, label = r"$f(x) = 2^x$")


pl.xlabel('x')
pl.ylabel("f(x)")
pl.legend()

pl.show()

The program will generate the plot of the three functions.

Note to return to the command line you must first close out of the resulting plot.

Matplotlib logo

Tech used:
  • Python
  • NumPy
  • Matplotlib.pyplot