## /usr/lib/python3/dist-packages/matplotlib/__init__.py:1352: UserWarning:  This call to matplotlib.use() has no effect
## because the backend has already been chosen;
## matplotlib.use() must be called *before* pylab, matplotlib.pyplot,
## or matplotlib.backends is imported for the first time.
## 
##   warnings.warn(_use_error_msg)

matplotlib

basic setup

import matplotlib.pyplot as plt
import numpy as np ## we almost always use matplotlib with numpy
x = np.arange(5)
plt.plot(x)

showing/saving plots

basic plots

y = np.array([1,3,2,4,8,5])
plt.plot(y)
plt.show(y)

plt.savefig("example1.png")
plt.close()

more principled plots

fig, ax = plt.subplots()
ax.plot(y)  ## create plot
fig.savefig("example2.png") ## save figure

scatter plots

fig, ax = plt.subplots()
np.random.seed(101)
x = np.random.randint(5,size=len(y))
ax.scatter(x,y)  ## create plot

Putting more than one thing on a plot

You can put more than one .plot() or .scatter() on the same set of axes

fig, ax = plt.subplots()
x = np.arange(0,5*np.pi,0.1)
y = np.sin(x)
ax.plot(x,y)
ax.plot(x+np.pi/2,y,color="red")

Modifying plot appearance

fig, ax = plt.subplots()
x = np.arange(0,5*np.pi,0.1)
y = np.sin(x)
ax.plot(x,y,marker="x",linestyle="--",color="purple")
ax.plot(x+np.pi/2,y,linewidth=2,color="blue")

More modifications

Shortcuts for color (first letter), marker, line style … see plot documentation

x = np.arange(0., 5., 0.2)
plt.plot(x, x, "r--")
plt.plot(x, x ** 2, "bs")
plt.plot(x, x ** 3, "g^")

More decorations

fig, ax = plt.subplots()
x = np.arange(0,5*np.pi,0.1)
y = np.sin(x)
ax.plot(x,y,label="first")
ax.plot(x+np.pi/2,y,color="red",label="second");
ax.set_xlim([0,25])
ax.legend(fontsize=8)
ax.set_xlabel("the x-axis label")
ax.set_ylabel("the y-axis label")
fig.suptitle("my plot")

other plot types

fig, ax = plt.subplots()
cat = np.array(["a", "b", "c", "d", "e"])
values = np.random.randint(10, size=5)
x_pos = np.arange(len(values))
ax.set_xticklabels(cat);
ax.bar(x_pos,values);
fig.savefig("bar.png")

bar plot

histograms

fig, ax = plt.subplots()
f = open("../data/cherrytree.txt", "r")
height = []
diam = []
for L in f:
    vals = np.array(L.split(),dtype="float")
    diam.append(vals[1])
    height.append(vals[2])
ax.hist(height);
fig.savefig("hist.png")

better bin widths

fig, ax = plt.subplots()
ax.hist(height,bins=6);
fig.savefig("hist2.png")

multiple subfigures in a plot

fig, ax = plt.subplots(1,3)
fig.set_size_inches((6,3))
ax[0].hist(height,bins=6);
## (array([4., 2., 5., 7., 9., 4.]), array([63., 67., 71., 75., 79., 83., 87.]), <a list of 6 Patch objects>)
ax[0].set_xlabel("height")
ax[1].hist(diam,bins=6);
## (array([ 3., 12.,  7.,  3.,  5.,  1.]), array([ 8.3 , 10.35, 12.4 , 14.45, 16.5 , 18.55, 20.6 ]), <a list of 6 Patch objects>)
ax[1].set_xlabel("diameter")
ax[2].scatter(height,diam)
ax[1].set_xlabel("height")
ax[2].set_xlabel("diameter")
fig.savefig("hist3.png")

The logistic map

logistic function

def logist_map(r,nt=100,x0=0.5):
   """ run the logistic map """
   x = np.zeros(nt)
   x[0] = x0
   for t in range(1,nt):
      x[t] = r*x[t-1]*(1-x[t-1])
   return(x)

x = logist_map(r=1.5, nt=8)
print(x[:4],"\n",x[4:])
## [0.5        0.375      0.3515625  0.34194946] 
##  [0.33753004 0.33540527 0.33436286 0.33384651]

It’s easier if we plot the sequences:

fig, ax = plt.subplots()
y1 = logist_map(1.5)
y2 = logist_map(2)
y3 = logist_map(3)
ax.plot(y1)
ax.plot(y2)
ax.plot(y3,'r')
fig.savefig("pix/lm0.png")


What if we make a function to do this?


rvals = np.arange(1.1,3.9,0.05)
b = np.zeros((500,len(rvals)))
for i in range(len(rvals)):
   b[:,i] = logist_map(r=rvals[i],nt=500)

fig, ax = plt.subplots()
rmat = np.tile(rvals,(500,1))
ax.scatter(rmat,b)
fig.savefig("pix/lm1.png")

now without the transient

fig,ax = plt.subplots()
b2 = b[250:,]
rmat2 = np.tile(rvals,(250,1))
ax.scatter(rmat2,b2)
fig.savefig("pix/lm2.png")

now as an image plot

fig,ax = plt.subplots()
ax.imshow(b2,aspect="auto",extent=[1.1,3.9,250,500],interpolation="none")
fig.savefig("pix/lm3.png")