Plotting in Python: Examples and Exercises

First some imports:


In [1]:
import numpy as np
import matplotlib.pyplot as plt

Now some examples --- please read this code first.


In [2]:
x = np.linspace(-6, 6, 200)
y = np.minimum(np.sin(x), np.cos(x))

In [3]:
fig, ax = plt.subplots()
ax.plot(x, y)
plt.show()


Here's a plot with two curves.


In [4]:
y1 = np.minimum(np.sin(x), np.cos(x))
y2 = np.maximum(np.sin(x), np.cos(x))

In [5]:
fig, ax = plt.subplots()
ax.plot(x, y1, label='y1')
ax.plot(x, y2, label='y2')
ax.legend()

plt.show()


Exercise 1

Plot the tent map

$$ f(x) = \mu \min\{x, 1 - x\} $$

on the interval $[0, 1]$ when $\mu = 1.8$


In [6]:
for i in range(15):
    print("solution below")


solution below
solution below
solution below
solution below
solution below
solution below
solution below
solution below
solution below
solution below
solution below
solution below
solution below
solution below
solution below

In [7]:
μ = 1.8
x = np.linspace(0, 1, 200)
y = μ * np.minimum(x, 1 - x)

In [8]:
fig, ax = plt.subplots()
ax.plot(x, y)
plt.show()


Exercise 2

The following example makes an empty array of length 3 and then fills them with the numbers 0.5, 1.0, 0.5:


In [9]:
x = np.empty(3)
x[0] = 0.5
x[1] = 1.0
x[2] = 0.5

In [10]:
x


Out[10]:
array([ 0.5,  1. ,  0.5])

The next code shows what the range() function does:


In [11]:
for i in range(5):
    print(i)


0
1
2
3
4

Now compute the time series of length 500 given by

$$ x_{t+1} = f(x_t) $$

where $f$ is as given above and $x_0 = 0.2$. Plot $x_t$ against $t$.


In [12]:
for i in range(15):
    print("solution below")


solution below
solution below
solution below
solution below
solution below
solution below
solution below
solution below
solution below
solution below
solution below
solution below
solution below
solution below
solution below

In [13]:
n = 500
x = np.empty(n)
x[0] = 0.2
for t in range(n-1):
    x[t+1] = μ * min(x[t], 1 - x[t])

In [14]:
fig, ax = plt.subplots()
ax.plot(range(n), x)
plt.show()


Exercise 3

The next code shows how to build a histogram.


In [15]:
z = np.random.randn(1000)
fig, ax = plt.subplots()
ax.hist(z, bins=40)
plt.show()


Now recompute the time series from the tent map, this time with $n=500,000$, and histogram it.


In [16]:
for i in range(15):
    print("solution below")


solution below
solution below
solution below
solution below
solution below
solution below
solution below
solution below
solution below
solution below
solution below
solution below
solution below
solution below
solution below

In [17]:
n = 1_000_000
x = np.empty(n)
x[0] = 0.2
for t in range(n-1):
    x[t+1] = μ * min(x[t], 1 - x[t])

In [18]:
fig, ax = plt.subplots()
ax.hist(x, bins=40)
plt.show()