Plotting

In order to do inline plotting within a notebook, ipython needs a magic command, commands that start with the %


In [ ]:
%matplotlib inline

Importing some modules (libraries) and giving them short names such as np and plt. You will find that most users will use these common ones.


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

It might be tempting to import a module in a blank namespace, to make for "more readable code" like the following example:

    from math import *
    s2 = sqrt(2)

but the danger of this is that importing multiple modules in blank namespace can make some invisible, plus obfuscates the code where the function came from. So it is safer to stick to import where you get the module namespace (or a shorter alias):

    import math
    s2 = math.sqrt(2)

Line plot

The array $x$ will contain numbers from 0 to 9.5 in steps of 0.5. We then compute two arrays $y$ and $z$ as follows: $$ y = {1\over{10}}{x^2} $$ and $$ z = 3\sqrt{x} $$


In [ ]:
x = 0.5*np.arange(20)
y = x*x*0.1
z = np.sqrt(x)*3

In [ ]:
plt.plot(x,y,'o-',label='y')
plt.plot(x,z,'*--',label='z')
plt.title("$x^2$ and $\sqrt{x}$")
#plt.legend(loc='best')
plt.legend()
plt.xlabel('X axis')
plt.ylabel('Y axis')
#plt.xscale('log')
#plt.yscale('log')
#plt.savefig('sample1.png')

Scatter plot


In [ ]:
plt.scatter(x,y,s=40.0,c='r',label='y')
plt.scatter(x,z,s=20.0,c='g',label='z')
plt.legend(loc='best')
plt.show()

Multi planel plots|


In [ ]:
fig = plt.figure()
fig1 = fig.add_subplot(121)
fig1.scatter(x,z,s=20.0,c='g',label='z')
fig2 = fig.add_subplot(122)
fig2.scatter(x,y,s=40.0,c='r',label='y');

Histogram


In [ ]:
n = 100000
mean = 4.0
disp = 2.0
bins = 32
g = np.random.normal(mean,disp,n)
p = np.random.poisson(mean,n)

In [ ]:
gh=plt.hist(g,bins)

In [ ]:
ph=plt.hist(p,bins)

In [ ]:
plt.hist([g,p],bins)

Notice that in this example the output from the plt.hist() command was not captured in a variable, but instead send to the output. You can see it contains the values and edges of the bins it computed. Of course this is also documented! http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.hist

Lots examples of plots and corresponding code on matplotlib's gallery:

http://matplotlib.org/gallery.html