There are many tools for plotting in Python. We will use here pyplot which is part of matplotlib. It is very standard, and a lot like Matlab. (But see also Bokeh and D3 plotting.)
We need a special command, inline to tell matplotlib to draw on our browser screen. Then we can load in the toolbox for pyplot.
I am going to be lazy and just import everything in pyplot, without and namespace encodings. This is considered sloppy coding, but it is okay for short, interactive notebooks.
In [35]:
%matplotlib inline
import numpy as np
from matplotlib.pyplot import *
Here is about the simplest plot command you can get.
In [36]:
plot([1,2,3,4])
Out[36]:
You can also plot y versus x values, as follows:
In [37]:
plot([1,2,3,4],[1,4,9,16])
Out[37]:
You can use various modifiers to get different styles of plots.
In [38]:
plot([1,2,3,4],[1,4,9,16],'or') # 'o' for dots, 'r' for red
Out[38]:
A scatter plot is also available:
In [39]:
scatter([1,2,3,4],[1,4,9,16])
Out[39]:
In [40]:
from numpy import *
In [41]:
x = linspace(-2,2)
y = x**3-x
plot(x,y)
Out[41]:
Let's get fancy and draw a figure with subplots.
The trick is to create a figure then use the add_subplot command to include each subplot. Each subplot can have its own labels, colours, etc.
The number 131 (in subplot) tells us that there will be 1 row and 3 columns in the figure, and we are inserting the 1st subplot.
In [42]:
x = linspace(-3,3)
fig = figure(figsize=figaspect(0.2))
ax = fig.add_subplot(131)
ax.plot(x,cos(x),color='b')
ax.set_title('Cosine')
ax = fig.add_subplot(132)
ax.plot(x,sin(x),color='r')
ax.set_title('Sine')
ax = fig.add_subplot(133)
ax.plot(x,cos(x),'b',x,sin(x),'r')
ax.set_title('Both')
Out[42]:
In [43]:
fig, ax = subplots()
num = 1000
s = 121
x1 = linspace(-0.5,1,num) + (0.5 - random.rand(num))
y1 = linspace(-5,5,num) + (0.5 - random.rand(num))
x2 = linspace(-0.5,1,num) + (0.5 - random.rand(num))
y2 = linspace(5,-5,num) + (0.5 - random.rand(num))
x3 = linspace(-0.5,1,num) + (0.5 - random.rand(num))
y3 = (0.5 - random.rand(num))
ax.scatter(x1, y1, color='r', s=2*s, marker='^', alpha=.4)
ax.scatter(x2, y2, color='b', s=s/2, marker='o', alpha=.4)
ax.scatter(x3, y3, color='g', s=s/3, marker='s', alpha=.4)
Out[43]:
In [ ]: