%pylab inline
Populating the interactive namespace from numpy and matplotlib
from __future__ import print_function
from __future__ import division
linspace(0, 2*pi, 10)
array([ 0. , 0.6981317 , 1.3962634 , 2.0943951 , 2.7925268 , 3.4906585 , 4.1887902 , 4.88692191, 5.58505361, 6.28318531])
x = linspace(0, 2 * pi, 100)
y = sin(x)
plot(x,y);
x = linspace(0, 2 * pi, 100)
y = sin(x)
plot(x,y);
grid()
x = linspace(0, 2 * pi, 100)
y = sin(x)
grid()
xlabel('angle (rad)')
ylabel('sin()')
title('The Sine Function')
plot(x,y);
x = linspace(0, 2 * pi, 100)
y = sin(x)
grid()
xlabel('angle (rad)', fontsize=20)
ylabel('sin()', fontsize=20)
title('The Sine Function', fontsize=24)
plot(x,y);
linspace(0, 2*pi, 5)
#['0', '$\pi/2$', '$\pi$', '$3\pi/2$', '$2\pi$']
array([ 0. , 1.57079633, 3.14159265, 4.71238898, 6.28318531])
x = linspace(0, 2 * pi, 100)
y = sin(x)
grid()
xlabel('angle (rad)')
ylabel('sin()')
title('The Sine Function')
xticks(linspace(0, 2*pi, 5), ['0', '$\pi/2$', '$\pi$', '$3\pi/2$', '$2\pi$'])
plot(x,y);
x = linspace(0, 2 * np.pi, 100)
y = sin(x)
xlabel('angle (rad)')
ylabel('sin()')
title('The Sine Function')
plot(x,y)
ax = gca() # gca stands for 'get current axis'
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data',0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data', 0))
xticks(linspace(0, 2*np.pi, 5), ['', '$\pi/2$', '$\pi$', '$3\pi/2$', '$2\pi$']);
t = 2 * np.pi / 3
x = linspace(0, 2 * np.pi, 100)
y = sin(x)
plot(x,y)
grid()
plot([t, t], [0, sin(t)], color='green', linewidth=2.5, linestyle="--")
scatter([t, ], [sin(t), ], 50, color='green')
annotate(r'$sin(\frac{2\pi}{3})=\frac{\sqrt{3}}{2}$',
xy=(t, np.sin(t)), xycoords='data',
xytext=(+10, +25), textcoords='offset points', fontsize=16,
arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"));
x = linspace(0, 2 * np.pi, 100)
y = sin(x)
grid()
xlabel('angle (rad)')
ylabel('sin()')
title('The Sine Function')
xlim( (0.5, 2) )
ylim((0, 1.1))
plot(x,y);
plot(np.random.rand(20))
[<matplotlib.lines.Line2D at 0x7faa52ca8550>]
plot(np.random.rand(20), 'o-.')
[<matplotlib.lines.Line2D at 0x7faa52682390>]
plot(np.random.rand(20), 'kx:')
[<matplotlib.lines.Line2D at 0x7faa524d8fd0>]
plot(np.random.rand(20), 'o-', lw=8)
[<matplotlib.lines.Line2D at 0x7faa523fba90>]
plot(np.random.rand(20), 'x-.', ms=30)
[<matplotlib.lines.Line2D at 0x7faa523a0410>]
plot(np.random.rand(20), 'o-.', ms=30, lw=8, alpha=0.7, mfc='white')
[<matplotlib.lines.Line2D at 0x5094990>]
Matplotlib gallery: http://matplotlib.org/gallery.html
If you are not using inline graphs, the graph GUI will allow some configuration options
x = linspace(1, 5, 50)
data = x**2 + rand(x.size)
plot(x, data);
semilogy(x,data);
semilogx(x,data);
loglog(x, data, );
clf() # for interactive graphs, clears
figure() # opens a new window
<matplotlib.figure.Figure at 0x7faa521d0e50>
<matplotlib.figure.Figure at 0x7faa522e7cd0>
<matplotlib.figure.Figure at 0x7faa521d0e50>
loglog(x, data);
loglog(x,x);
loglog(x,x**2);
loglog(x,x**3, color='black');
x = linspace(0, 2 * np.pi, 100)
y = sin(x)
grid()
plot(x,y)
xlabel('angle (rad)')
ylabel('sin()')
title('The Sine Function')
xticks(linspace(0, 2*np.pi, 5), ['0', '$\pi/2$', '$\pi$', '$3\pi/2$', '$2\pi$'])
savefig('output.pdf')
In the notebook, the savefig instruction must be within the same cell. In other interactive modes, it saves the currently active figure.
You can save different formats, including pdf, svg, png and eps.
Full call signature:
savefig(fname, dpi=None, facecolor='w', edgecolor='w',
orientation='portrait', papertype=None, format=None,
transparent=False, bbox_inches=None, pad_inches=0.1,
frameon=None)
You can create multiple plots within a figure with the subplot command.
x = linspace(0, 2 * np.pi, 100)
y = sin(x)
grid()
subplot(1,2,1)
plot(x,y)
xlabel('angle (rad)')
ylabel('sin()')
title('The Sine Function')
subplot(1,2,2)
plot(x,cos(x))
xlabel('angle (rad)')
ylabel('cos()')
title('The Cosine Function')
suptitle('Trigonometric functions');
As you can see you might often need to ajust proprotions a locations of plots...
You can do it from the GUI if you are using the external matplotlib window from an interactive shell, but in the notebook you have to do it programatically.
x = linspace(0, 2 * np.pi, 100)
y = sin(x)
grid()
subplot(1,2,1)
plot(x,y)
xlabel('angle (rad)')
ylabel('sin()')
title('The Sine Function')
subplot(1,2,2)
plot(x,cos(x))
xlabel('angle (rad)')
ylabel('cos()')
title('The Cosine Function')
suptitle('Trigonometric functions')
gcf().set_figwidth(14)
As you can see, this is done to the "current" figure, which is returned with gcf() (Get Current Figure).
Full (very full... ) documentation here: http://matplotlib.org/api/figure_api.html
You can adjust subplots with:
subplots_adjust(left=None, bottom=None, right=None, top=None,
wspace=None, hspace=None)
x = linspace(0, 2 * np.pi, 100)
y = sin(x)
grid()
subplot(1,2,1)
plot(x,y)
xlabel('angle (rad)')
ylabel('sin()')
title('The Sine Function')
subplot(1,2,2)
plot(x,cos(x))
xlabel('angle (rad)')
ylabel('cos()')
title('The Cosine Function')
suptitle('Trigonometric functions')
subplots_adjust(wspace=2)
Here's another way:
x = linspace(0, 2 * np.pi, 100)
y = sin(x)
grid()
subplot(1,2,1)
plot(x,y)
xlabel('angle (rad)')
ylabel('sin()')
title('The Sine Function')
subplot(1,2,2)
plot(x,cos(x))
xlabel('angle (rad)')
ylabel('cos()')
title('The Cosine Function')
suptitle('Trigonometric functions')
w, h = figaspect(0.3)
gcf().set_figwidth(w)
gcf().set_figheight(h)
x = linspace(0, 2 * np.pi, 100)
plot(x,sin(x))
plot(x,cos(x));
For publishing, you might want to have black lines with different strokes:
x = linspace(0, 2 * np.pi, 100)
plot(x,sin(x), 'k')
plot(x,cos(x), 'k-.')
plot(x,sin(2*x), 'k,')
[<matplotlib.lines.Line2D at 0x7faa5230f450>]
x = linspace(0, 2 * np.pi, 100)
plot(x,sin(x), 'k')
plot(x,cos(x), 'k-.')
plot(x,sin(2*x), 'k,')
names = ['sin($\omega$)', 'cos($\omega$)', 'sin($2\omega$)']
legend(names);
xlim((0, 2*np.pi))
(0, 6.283185307179586)
x = linspace(0, 2 * np.pi, 100)
plot(x,sin(x), 'ko')
plot(x,cos(x), 'k^')
plot(x,sin(2*x), 'kx')
names = ['sin($\omega$)', 'cos($\omega$)', 'sin($2\omega$)']
legend(names)
<matplotlib.legend.Legend at 0x7faa520a9110>
samples = poisson(lam= 3.5, size= 500)
hist(samples)
(array([ 67., 96., 112., 86., 75., 52., 6., 5., 0., 1.]), array([ 0. , 1.2, 2.4, 3.6, 4.8, 6. , 7.2, 8.4, 9.6, 10.8, 12. ]), <a list of 10 Patch objects>)
hist(samples, 5)
(array([ 163., 198., 127., 11., 1.]), array([ 0. , 2.4, 4.8, 7.2, 9.6, 12. ]), <a list of 5 Patch objects>)
For publication, you might need to adjust:
hist(samples, 5, histtype='step', align= 'left', color= 'k', normed=True, hatch='\\')
xticks(arange(5)*2, ['A', 'B', 'C', 'D', 'E'])
grid()
hist(samples, 20, histtype='step', align= 'left', color= 'k', orientation='horizontal', normed=True, hatch='\\')
yticks(arange(10), ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J']);
bar(arange(12), random.random(12), 0.55);
ind = arange(12)
width = 1
bar(ind, random.random(12), width)
xticks(ind+width/2., ind );
mat = rand(10,10)
imshow(mat);
imshow(mat, cmap=cm.gray)
<matplotlib.image.AxesImage at 0x7faa52085710>
imshow(mat)
colorbar();
imshow(mat, cmap=cm.gray)
colorbar();
imshow(mat, cmap=cm.gray, interpolation='nearest')
colorbar();
subplot(1,4,1)
imshow(mat, interpolation='nearest')
grid(True)
subplot(1,4,2)
imshow(mat, interpolation='bilinear')
subplot(1,4,3)
imshow(mat, interpolation='bicubic')
subplot(1,4,4)
imshow(mat, interpolation='gaussian')
gcf().set_figwidth(14)
imshow(mat, interpolation='nearest')
plot(mat[5] + 4.5, 'white', linewidth=5)
colorbar();
xlim((-0.5, 9.5))
ylim((9.5, -0.5))
(9.5, -0.5)
N=100
x = np.random.randn(N)
y = np.random.randn(N)
scatter(x,y)
<matplotlib.collections.PathCollection at 0x7faa4bff9ed0>
N=100
x = np.random.randn(N)
y = np.random.randn(N)
scatter(x,y,color='blue',s=5,edgecolor='none')
<matplotlib.collections.PathCollection at 0x7faa501272d0>
N=100
x = np.random.randn(N)
y = np.random.randn(N)
scatter(x,y,color='blue',s=40,edgecolor='none', marker=7)
<matplotlib.collections.PathCollection at 0x7faa5001f890>
dict(alpha=0.5, edgecolors='none' )
{'alpha': 0.5, 'edgecolors': 'none'}
d = {'alpha': 0.5, 'edgecolors': 'none'}
print(d)
d['alpha'] = 'hello'
print(d)
{'alpha': 0.5, 'edgecolors': 'none'} {'alpha': 'hello', 'edgecolors': 'none'}
props = dict(alpha=0.5, edgecolors='none', c='blue' )
scatter(x, y, s=20, **props)
props = dict(alpha=0.8, c='red' )
scatter(y,x, s=20, **props)
# scatter(x, y, c='red', s=20, alpha=0.5, edgecolors='none')
<matplotlib.collections.PathCollection at 0x7faa4be13950>
props
{'alpha': 0.8, 'c': 'red'}
N = 10
props = dict(alpha=0.5, edgecolors='none' )
handles = []
colors = ['red', 'blue', 'brown', 'green']
for color in colors:
x = np.random.randn(N)
y = np.random.randn(N)
s = np.random.randint(10,300)
handles.append(scatter(x, y, c=color, s=s, **props))
ylim([-5,11])
xlim([-5,11])
legend(handles, colors)
grid(True)
text(0.5, 0.5, 'text')
<matplotlib.text.Text at 0x7faa4beaf850>
# the text bounding box
bbox = {'facecolor':'0.9', 'alpha':0.7, 'pad':40, 'color':'red'}
props = {'ha':'center', 'va':'center', 'fontsize': 20, 'bbox':bbox}
text(0.5, 0.5, 'text 0', props, rotation=0)
text(1.5, 0.5, 'text 45', props, rotation=45)
text(2.5, 0.5, 'text 135', props, rotation=135, family='Serif')
text(3.5, 0.5, 'text 225', props, rotation=225)
text(4.5, 0.5, 'text -45', props, rotation=-45, family='Serif')
yticks([0,.5,1])
xlim(0,5)
xticks(arange(0, 5.1, 0.5), [])
ylabel('center / center')
<matplotlib.text.Text at 0x7faa4bcddfd0>
from mpl_toolkits.mplot3d import Axes3D
fig = figure()
ax = Axes3D(fig)
X = arange(-4, 4, 0.25)
Y = arange(-4, 4, 0.25)
X, Y = meshgrid(X, Y)
R = sqrt(X ** 2 + Y ** 2)
Z = sin(R)
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.hot)
ax.contourf(X, Y, Z, zdir='z', offset=-2, cmap=cm.hot)
ax.set_zlim(-2, 2)
grid()
Another simple tutorial for graphing with ipython: http://nbviewer.ipython.org/github/swcarpentry/notebooks/blob/master/matplotlib.ipynb
Comprehensive tutorial: http://scipy-lectures.github.io/intro/matplotlib/matplotlib.html
The Matplotlib gallery is a great place to find ideas: http://matplotlib.org/gallery.html
By Andrés Cabrera mantaraya36@gmail.com
For course MAT 201A at UCSB
This ipython notebook is licensed under the CC-BY-NC-SA license: http://creativecommons.org/licenses/by-nc-sa/4.0/