Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupport News AboutSign UpSign In
| Download

Tutorials

Views: 1300
Kernel: Python 3 (Ubuntu Linux)

Functions and Plotting

In this notebook you will find some examples on working with functions and basic plotting using numpy and pyplot. Documentation can be found here and here.

# import the required modules import numpy as np import matplotlib.pyplot as plt

Elementary operations

We will frequently be computing with arrays of numbers, so let's see how various elementary computations are defined

# define array x = np.array([1,2,3,4]) # inspect the array print(x)
[1 2 3 4]
# elementary operations with two arrays y = np.array([5,6,7,8]) print(x + y)
[ 6 8 10 12]

Exercise

Try various elementary operations (+,-,*,/). What do the operations x**2 and x**y produce? And how about x^2?

Univariate functions

To plot a function ff we first need to evaluate it at a number of points xix_i and subsequently produce a plot.

# uniform grid of 100 points on [-1,1] x = np.linspace(-1,1,100) # plot sine and cosine plt.plot(x,np.sin(x),x,np.cos(x))
[<matplotlib.lines.Line2D at 0x7f3e41edacc0>, <matplotlib.lines.Line2D at 0x7f3e41edaeb8>]
Image in a Jupyter notebook

We can add labels, a legend and change the linestyle of the plots:

# uniform grid of 100 points on [-1,1] x = np.linspace(-1,1,100) # plot sine and cosine plt.plot(x,np.sin(x),'r-',x,np.cos(x),'k--') plt.xlabel('x') plt.ylabel('f(x)') plt.legend(('sin(x)','cos(x)'))
<matplotlib.legend.Legend at 0x7f3e18119f60>
Image in a Jupyter notebook

Defining your own functions

We can define our own functions as follows

# define f(x) = x^2 f = lambda x : x**2 # define piecewise function (uses list comprehension and conditional expression) g = lambda x : np.array([s if s > 0 else s**2 for s in x]) # plot x = np.linspace(-1,1,100) plt.plot(x,f(x),x,g(x))
[<matplotlib.lines.Line2D at 0x7f3e115b0908>, <matplotlib.lines.Line2D at 0x7f3e115b0a90>]
Image in a Jupyter notebook

Exercise

Define the function ParseError: KaTeX parse error: Unknown column alignment: - at position 29: …{\begin{array} -̲-x & x < -1 \\ …

and plot it.

Multivariate functions

When plotting a function of two variables, we need to define a grid (xi,yi)(x_i, y_i) first:

# define grid with 100 x 100 points on [0,1]^2 x = np.linspace(0,1,100) y = np.linspace(0,1,100) xx,yy = np.meshgrid(x,y) # define function f = lambda x,y : np.exp(-(x - .5)**2-5*(y-.2)**2) # various ways of plotting plt.subplot(121) plt.contour(xx,yy,f(xx,yy)) plt.axis('square') plt.subplot(122) plt.contourf(xx,yy,f(xx,yy)) plt.axis('square')
(0.0, 1.0, 0.0, 1.0)
Image in a Jupyter notebook