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)
grid()
plot(x,y);
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$']
['0', '$\\pi/2$', '$\\pi$', '$3\\pi/2$', '$2\\pi$']
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 0x4b28a50>]
plot(np.random.rand(20), 'o-.')
[<matplotlib.lines.Line2D at 0x4226310>]
plot(np.random.rand(20), 'kx-.')
[<matplotlib.lines.Line2D at 0x4b4bf90>]
plot(np.random.rand(20), 'o-', lw=8)
[<matplotlib.lines.Line2D at 0x4d562d0>]
plot(np.random.rand(20), 'x-.', ms=30)
[<matplotlib.lines.Line2D at 0x5073190>]
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
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(18)
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 0x653fdd0>]
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);
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 0x6b64e50>
samples = poisson(lam= 3.5, size= 500)
hist(samples)
(array([ 17, 51, 100, 112, 86, 65, 35, 26, 6, 2]), array([ 0., 1., 2., 3., 4., 5., 6., 7., 8., 9., 10.]), <a list of 10 Patch objects>)
hist(samples, 5)
(array([ 68, 212, 151, 61, 8]), array([ 0., 2., 4., 6., 8., 10.]), <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)
<Container object of 12 artists>
ind = arange(12)
width = 0.9
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 0x79adf10>
imshow(ma)
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(20)
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 0x7c9d4d0>
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 0x87026d0>
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 0x825c4d0>
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 0x86f7f90>
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 0x8188e10>
# 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 0x879c110>
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(
(-2, 2)
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 240E at UCSB
This ipython notebook is licensed under the CC-BY-NC-SA license: http://creativecommons.org/licenses/by-nc-sa/4.0/