#!/usr/bin/env python
"""
Example: simple line plot.
Show how to make and save a simple line plot with labels, title and grid
"""
from pylab import *
t = arange(0.0, 1.0+0.01, 0.01)
s = cos(2*2*pi*t)
plot(t, s, '-', lw=2)
xlabel('time (s)')
ylabel('voltage (mV)')
title('About as simple as it gets, folks')
grid(True)
#savefig('simple_plot.png')
savefig('simple_plot')
show()
#!/usr/bin/env python
"""
Make a pie chart - see
http://matplotlib.sf.net/matplotlib.pylab.html#-pie for the docstring.
This example shows a basic pie chart with labels in figure 1, and
figure 2 uses a couple of optional features, like autolabeling the
area percentage, offsetting a slice using "explode" and addind a shadow
for a 3D effect
"""
from pylab import *
# make a square figure and axes
figure(1, figsize=(8,8))
ax = axes([0.1, 0.1, 0.8, 0.8])
labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
fracs = [15,30,45, 10]
figure(1)
pie(fracs, labels=labels)
# figure(2) showa some optional features. autopct is used to label
# the percentage of the pie, and can be a format string or a function
# which takes a percentage and returns a string. explode is a
# len(fracs) sequuence which gives the fraction of the radius to
# offset that slice.
figure(2, figsize=(8,8))
explode=(0, 0.05, 0, 0)
pie(fracs, explode=explode, labels=labels, autopct='%1.1f%%', shadow=True)
savefig('pie_demo')
show()
from pylab import *
from matplotlib.patches import Ellipse
delta = 45.0 # degrees
angles = arange(0, 360+delta, delta)
ells = [Ellipse((1, 1), 4, 2, a) for a in angles]
a = subplot(111, aspect='equal')
for e in ells:
e.set_clip_box(a.bbox)
e.set_alpha(0.1)
a.add_artist(e)
xlim(-2, 4)
ylim(-1, 3)
show()
#!/usr/bin/env python
# make a horizontal bar chart
from pylab import *
val = 3+10*rand(5) # the bar lengths
pos = arange(5)+.5 # the bar centers on the y axis
figure(1)
barh(pos,val, align='center')
yticks(pos, ('Tom', 'Dick', 'Harry', 'Slim', 'Jim'))
xlabel('Perfomance')
title('How fast do you want to go today?')
grid(True)
figure(2)
barh(pos,val, xerr=rand(5), ecolor='r', align='center')
yticks(pos, ('Tom', 'Dick', 'Harry', 'Slim', 'Jim'))
xlabel('Perfomance')
show()
#!/usr/bin/env python
"""
matplotlib gives you 4 ways to specify colors,
1) as a single letter string, ala matlab
2) as an html style hex string or html color name
3) as an R,G,B tuple, where R,G,B, range from 0-1
4) as a string representing a floating point number
from 0 to 1, corresponding to shades of gray.
See help(colors) for more info.
"""
from pylab import *
subplot(111, axisbg='darkslategray')
#subplot(111, axisbg='#ababab')
t = arange(0.0, 2.0, 0.01)
s = sin(2*pi*t)
plot(t, s, 'y')
xlabel('time (s)', color='r')
ylabel('voltage (mV)', color='0.5') # grayscale color
title('About as silly as it gets, folks', color='#afeeee')
show()
#!/usr/bin/env python
"""
This example shows how to use matplotlib to provide a data cursor. It
uses matplotlib to draw the cursor and may be a slow since this
requires redrawing the figure with every mouse move.
Faster cursoring is possible using native GUI drawing, as in
wxcursor_demo.py
"""
from pylab import *
class Cursor:
def __init__(self, ax):
self.ax = ax
self.lx, = ax.plot( (0,0), (0,0), 'k-' ) # the horiz line
self.ly, = ax.plot( (0,0), (0,0), 'k-' ) # the vert line
# text location in axes coords
self.txt = ax.text( 0.7, 0.9, '', transform=ax.transAxes)
def mouse_move(self, event):
if not event.inaxes: return
ax = event.inaxes
minx, maxx = ax.get_xlim()
miny, maxy = ax.get_ylim()
x, y = event.xdata, event.ydata
# update the line positions
self.lx.set_data( (minx, maxx), (y, y) )
self.ly.set_data( (x, x), (miny, maxy) )
self.txt.set_text( 'x=%1.2f, y=%1.2f'%(x,y) )
draw()
class SnaptoCursor:
"""
Like Cursor but the crosshair snaps to the nearest x,y point
For simplicity, I'm assuming x is sorted
"""
def __init__(self, ax, x, y):
self.ax = ax
self.lx, = ax.plot( (0,0), (0,0), 'k-' ) # the horiz line
self.ly, = ax.plot( (0,0), (0,0), 'k-' ) # the vert line
self.x = x
self.y = y
# text location in axes coords
self.txt = ax.text( 0.7, 0.9, '', transform=ax.transAxes)
def mouse_move(self, event):
if not event.inaxes: return
ax = event.inaxes
minx, maxx = ax.get_xlim()
miny, maxy = ax.get_ylim()
x, y = event.xdata, event.ydata
indx = searchsorted(self.x, [x])[0]
x = self.x[indx]
y = self.y[indx]
# update the line positions
self.lx.set_data( (minx, maxx), (y, y) )
self.ly.set_data( (x, x), (miny, maxy) )
self.txt.set_text( 'x=%1.2f, y=%1.2f'%(x,y) )
print 'x=%1.2f, y=%1.2f'%(x,y)
draw()
t = arange(0.0, 1.0, 0.01)
s = sin(2*2*pi*t)
ax = subplot(111)
cursor = Cursor(ax)
#cursor = SnaptoCursor(ax, t, s)
connect('motion_notify_event', cursor.mouse_move)
ax.plot(t, s, 'o')
axis([0,1,-1,1])
show()
#!/usr/bin/env python
"""
You can precisely specify dashes with an on/off ink rect sequence in
points.
"""
from pylab import *
dashes = [5,2,10,5] # 5 points on, 2 off, 3 on, 1 off
l, = plot(arange(20), '--')
l.set_dashes(dashes)
savefig('dash_control')
show()
#!/usr/bin/env python
from pylab import *
t = arange(0.0, 3.0, 0.05)
s = sin(2*pi*t)
styles = ('-', '--', ':', '.', 'o', '^', 'v', '<', '>', 's', '+')
colors = ('b', 'g', 'r', 'c', 'm', 'y', 'k')
axisNum = 0
for row in range(5):
for col in range(4):
s = sin(2*pi*t)
axisNum += 1
subplot(5,4,axisNum)
style = styles[axisNum % len(styles) ]
color = colors[axisNum % len(colors) ]
plot(t,s, style + color)
# turn off the ticklabels if not first row or first col
if not gca().is_first_col():
setp(gca(), 'yticklabels', [])
if not gca().is_last_row():
setp(gca(), 'xticklabels', [])
#savefig('line_styles', dpi=300)
show()
#!/usr/bin/env python
from pylab import *
x1 = arange(0, 2, 0.01)
y1 = sin(2*pi*x1)
y2 = sin(4*pi*x1) + 2
# reverse x and y2 so the polygon fills in order
x = concatenate( (x1,x1[::-1]) )
y = concatenate( (y1,y2[::-1]) )
p = fill(x, y, facecolor='g', alpha=0.5)
show()
#!/usr/bin/env python
from pylab import *
# create some data to use for the plot
dt = 0.001
t = arange(0.0, 10.0, dt)
r = exp(-t[:1000]/0.05) # impulse response
x = randn(len(t))
s = conv(x,r)[:len(x)]*dt # colored noise
# the main axes is subplot(111) by default
plot(t, s)
axis([0, 1, 1.1*amin(s), 2*amax(s) ])
xlabel('time (s)')
ylabel('current (nA)')
title('Gaussian colored noise')
# this is an inset axes over the main axes
a = axes([.65, .6, .2, .2], axisbg='y')
n, bins, patches = hist(s, 400, normed=1)
title('Probability')
setp(a, xticks=[], yticks=[])
# this is another inset axes over the main axes
a = axes([0.2, 0.6, .2, .2], axisbg='y')
plot(t[:len(r)], r)
title('Impulse response')
setp(a, xlim=(0,.2), xticks=[], yticks=[])
#savefig('../figures/axes_demo.eps')
#savefig('../figures/axes_demo.png')
show()
#!/usr/bin/env python
"""
To create plots that share a common axes (visually) you can set the
hspace bewtween the subplots close to zero (do not use zero itself).
Normally you'll want to turn off the tick labels on all but one of the
axes.
In this example the plots share a common xaxis but you can follow the
same logic to supply a common y axis.
"""
from pylab import *
t = arange(0.0, 2.0, 0.01)
s1 = sin(2*pi*t)
s2 = exp(-t)
s3 = s1*s2
# axes rect in relative 0,1 coords left, bottom, width, height. Turn
# off xtick labels on all but the lower plot
f = figure()
subplots_adjust(hspace=0.001)
ax1 = subplot(311)
ax1.plot(t,s1)
yticks(arange(-0.9, 1.0, 0.4))
ylim(-1,1)
ax2 = subplot(312, sharex=ax1)
ax2.plot(t,s2)
yticks(arange(0.1, 1.0, 0.2))
ylim(0,1)
ax3 = subplot(313, sharex=ax1)
ax3.plot(t,s3)
yticks(arange(-0.9, 1.0, 0.4))
ylim(-1,1)
xticklabels = ax1.get_xticklabels()+ax2.get_xticklabels()
setp(xticklabels, visible=False)
show()
"""
You can share the x or y axis limits for one axis with another by
passing an axes instance as a sharex or sharey kwarg.
Changing the axis limits on one axes will be reflected automatically
in the other, and vice-versa, so when you navigate with the toolbar
the axes will follow each other on their shared axes. Ditto for
changes in the axis scaling (eg log vs linear). However, it is
possible to have differences in tick labeling, eg you can selectively
turn off the tick labels on one axes.
The example below shows how to customize the tick labels on the
various axes. Shared axes share the tick locator, tick formatter,
view limits, and transformation (eg log, linear). But the ticklabels
themselves do not share properties. This is a feature and not a bug,
because you may want to make the tick labels smaller on the upper
axes, eg in the example below.
If you want to turn off the ticklabels for a given axes (eg on
subplot(211) or subplot(212), you cannot do the standard trick
setp(ax2, xticklabels=[])
because this changes the tick Formatter, which is shared among all
axes. But you can alter the visibility of the labels, which is a
property
setp( ax2.get_xticklabels(), visible=False)
"""
from pylab import *
t = arange(0.01, 5.0, 0.01)
s1 = sin(2*pi*t)
s2 = exp(-t)
s3 = sin(4*pi*t)
ax1 = subplot(311)
plot(t,s1)
setp( ax1.get_xticklabels(), fontsize=6)
## share x only
ax2 = subplot(312, sharex=ax1)
plot(t, s2)
# make these tick labels invisible
setp( ax2.get_xticklabels(), visible=False)
# share x and y
ax3 = subplot(313, sharex=ax1, sharey=ax1)
plot(t, s3)
xlim(0.01,5.0)
show()
#!/usr/bin/env python
"""
In order to use mathtext, you must build matplotlib.ft2font. This is
built by default in the windows installer.
For other platforms, edit setup.py and set
BUILD_FT2FONT = True
"""
from pylab import *
subplot(111, axisbg='y')
plot([1,2,3], 'r')
x = arange(0.0, 3.0, 0.1)
grid(True)
xlabel(r'$\Delta_i^j$', fontsize=20)
ylabel(r'$\Delta_{i+1}^j$', fontsize=20)
tex = r'$\cal{R}\prod_{i=\alpha_{i+1}}^\infty a_i\rm{sin}(2 \pi f x_i)$'
text(1, 1.6, tex, fontsize=20)
savefig('mathtext_demo')
show()
#!/usr/bin/env python
"""
You can use decreasing axes by flipping the normal order of the axis
limits
"""
from pylab import *
t = arange(0.01, 5.0, 0.01)
s = exp(-t)
plot(t, s)
xlim(5,0) # decreasing time
xlabel('decreasing time (s)')
ylabel('voltage (mV)')
title('Should be growing...')
grid(True)
show()
#!/usr/bin/env python
"""
Layer images above one another using alpha blending
"""
from __future__ import division
from pylab import *
def func3(x,y):
return (1- x/2 + x**5 + y**3)*exp(-x**2-y**2)
# make these smaller to increase the resolution
dx, dy = 0.05, 0.05
x = arange(-3.0, 3.0, dx)
y = arange(-3.0, 3.0, dy)
X,Y = meshgrid(x, y)
# when layering multiple images, the images need to have the same
# extent. This does not mean they need to have the same shape, but
# they both need to render to the same coordinate system determined by
# xmin, xmax, ymin, ymax. Note if you use different interpolations
# for the images their apparent extent could be different due to
# interpolation edge effects
xmin, xmax, ymin, ymax = amin(x), amax(x), amin(y), amax(y)
extent = xmin, xmax, ymin, ymax
Z1 = array(([0,1]*4 + [1,0]*4)*4); Z1.shape = 8,8 # chessboard
im1 = imshow(Z1, cmap=cm.gray, interpolation='nearest',
extent=extent)
hold(True)
Z2 = func3(X, Y)
im2 = imshow(Z2, cmap=cm.jet, alpha=.9, interpolation='bilinear',
extent=extent)
#axis([xmin, xmax, ymin, ymax])
#savefig('layer_images')
show()
#!/usr/bin/env python
"""
Set the major ticks on the ints and minor ticks on multiples of 0.2
"""
from pylab import *
from matplotlib.ticker import MultipleLocator, FormatStrFormatter
majorLocator = MultipleLocator(1)
majorFormatter = FormatStrFormatter('%d')
minorLocator = MultipleLocator(.2)
t = arange(0.0, 10.0, 0.01)
s = sin(2*pi*t)*exp(-t*0.01)
ax = subplot(111)
plot(t,s)
ax.xaxis.set_major_locator(majorLocator)
ax.xaxis.set_major_formatter(majorFormatter)
#for the minor ticks, use no labels; default NullFormatter
ax.xaxis.set_minor_locator(minorLocator)
show()
#!/bin/env python
'''
Plot lines with points masked out.
This would typically be used with gappy data, to
break the line at the data gaps.
'''
import matplotlib.numerix.ma as M
from pylab import *
x = M.arange(0, 2*pi, 0.02)
y = M.sin(x)
y1 = sin(2*x)
y2 = sin(3*x)
ym1 = M.masked_where(y1 > 0.5, y1)
ym2 = M.masked_where(y2 < -0.5, y2)
lines = plot(x, y, 'r', x, ym1, 'g', x, ym2, 'bo')
setp(lines[0], linewidth = 4)
setp(lines[1], linewidth = 2)
setp(lines[2], markersize = 10)
legend( ('No mask', 'Masked if > 0.5', 'Masked if < -0.5') ,
loc = 'upper right')
title('Masked line demo')
show()
#!/usr/bin/env python
"""
See pcolor_demo2 for an alternative way of generating pcolor plots
using imshow that is likely faster for large grids
"""
from __future__ import division
from matplotlib.patches import Patch
from pylab import *
def func3(x,y):
return (1- x/2 + x**5 + y**3)*exp(-x**2-y**2)
# make these smaller to increase the resolution
dx, dy = 0.05, 0.05
x = arange(-3.0, 3.0001, dx)
y = arange(-3.0, 3.0001, dy)
X,Y = meshgrid(x, y)
Z = func3(X, Y)
pcolor(X, Y, Z, shading='flat')
colorbar()
axis([-3,3,-3,3])
savefig('pcolor_demo')
show()
#!/usr/bin/env python
# a polar scatter plot; size increases radially in this example and
# color increases with angle (just to verify the symbols are being
# scattered correctlu). In a real example, this would be wasting
# dimensionlaity of the plot
from pylab import *
N = 150
r = 2*rand(N)
theta = 2*pi*rand(N)
area = 200*r**2*rand(N)
colors = theta
ax = subplot(111, polar=True)
c = scatter(theta, r, c=colors, s=area)
c.set_alpha(0.75)
#savefig('polar_test2')
show()
'''
Demonstration of quiver and quiverkey functions. This is using the
new version coming from the code in quiver.py.
Known problem: the plot autoscaling does not take into account
the arrows, so those on the boundaries are often out of the picture.
This is *not* an easy problem to solve in a perfectly general way.
The workaround is to manually expand the axes.
'''
from pylab import *
X,Y = meshgrid( arange(0,2*pi,.2),arange(0,2*pi,.2) )
U = cos(X)
V = sin(Y)
#1
figure()
Q = quiver( U, V)
qk = quiverkey(Q, 0.5, 0.92, 2, '2 m/s', labelpos='W',
fontproperties={'weight': 'bold'})
l,r,b,t = axis()
dx, dy = r-l, t-b
axis([l-0.05*dx, r+0.05*dx, b-0.05*dy, t+0.05*dy])
title('Minimal arguments, no kwargs')
#2
figure()
Q = quiver( X, Y, U, V, units='width')
qk = quiverkey(Q, 0.9, 0.95, 2, '2 m/s',
labelpos='E',
coordinates='figure',
fontproperties={'weight': 'bold'})
axis([-1, 7, -1, 7])
title('scales with plot width, not view')
#3
figure()
Q = quiver( X[::3, ::3], Y[::3, ::3], U[::3, ::3], V[::3, ::3],
pivot='mid', color='r', units='inches' )
qk = quiverkey(Q, 0.5, 0.03, 1, '1 m/s', fontproperties={'weight': 'bold'})
plot( X[::3, ::3], Y[::3, ::3], 'k.')
axis([-1, 7, -1, 7])
title("pivot='mid'; every third arrow; units='inches'")
#4
figure()
M = sqrt(pow(U, 2) + pow(V, 2))
Q = quiver( X, Y, U, V, M, units='x', pivot='tip', width=0.022, scale=1/0.15)
qk = quiverkey(Q, 0.9, 1.05, 1, '1 m/s',
labelpos='E',
fontproperties={'weight': 'bold'})
plot(X, Y, 'k.')
axis([-1, 7, -1, 7])
title("scales with x view; pivot='tip'")
#5
figure()
Q = quiver( X[::3, ::3], Y[::3, ::3], U[::3, ::3], V[::3, ::3],
color='r', units='x',
linewidths=(2,), edgecolors=('k'), headaxislength=5 )
qk = quiverkey(Q, 0.5, 0.03, 1, '1 m/s', fontproperties={'weight': 'bold'})
axis([-1, 7, -1, 7])
title("triangular head; scale with x view; black edges")
show()
#!/usr/bin/env python
from pylab import *
N = 30
x = 0.9*rand(N)
y = 0.9*rand(N)
area = pi*(10 * rand(N))**2 # 0 to 10 point radiuses
scatter(x,y,s=area, marker='^', c='r')
savefig('scatter_demo')
show()
#!/usr/bin/env python
from pylab import *
dt = 0.0005
t = arange(0.0, 20.0, dt)
s1 = sin(2*pi*100*t)
s2 = 2*sin(2*pi*400*t)
# create a transient "chirp"
mask = where(logical_and(t>10, t<12), 1.0, 0.0)
s2 = s2 * mask
# add some noise into the mix
nse = 0.01*randn(len(t))
x = s1 + s2 + nse # the signal
NFFT = 1024 # the length of the windowing segments
Fs = int(1.0/dt) # the sampling frequency
# Pxx is the segments x freqs array of instantaneous power, freqs is
# the frequency vector, bins are the centers of the time bins in which
# the power is computed, and im is the matplotlib.image.AxesImage
# instance
Pxx, freqs, bins, im = specgram(x, NFFT=NFFT, Fs=Fs, noverlap=900)
colorbar()
show()
#!/usr/bin/env python
import matplotlib
from pylab import *
from colours import get_colours
axes([0.2, 0.2, 0.7, 0.6]) # leave room below the axes for the table
data = [[ 66386, 174296, 75131, 577908, 32015],
[ 58230, 381139, 78045, 99308, 160454],
[ 89135, 80552, 152558, 497981, 603535],
[ 78415, 81858, 150656, 193263, 69638],
[ 139361, 331509, 343164, 781380, 52269]]
colLabels = ('Freeze', 'Wind', 'Flood', 'Quake', 'Hail')
rowLabels = ['%d year' % x for x in (100, 50, 20, 10, 5)]
# Get some pastel shades for the colours
colours = get_colours(len(colLabels))
colours.reverse()
rows = len(data)
ind = arange(len(colLabels)) + 0.3 # the x locations for the groups
cellText = []
width = 0.4 # the width of the bars
yoff = array([0.0] * len(colLabels)) # the bottom values for stacked bar chart
for row in xrange(rows):
bar(ind, data[row], width, bottom=yoff, color=colours[row])
yoff = yoff + data[row]
cellText.append(['%1.1f' % (x/1000.0) for x in yoff])
# Add a table at the bottom of the axes
colours.reverse()
cellText.reverse()
the_table = table(cellText=cellText,
rowLabels=rowLabels, rowColours=colours,
colLabels=colLabels,
loc='bottom')
ylabel("Loss $1000's")
vals = arange(0, 2500, 500)
yticks(vals*1000, ['%d' % val for val in vals])
xticks([])
title('Loss by Disaster')
#savefig('table_demo_small', dpi=75)
#savefig('table_demo_large', dpi=300)
show()
#!/usr/bin/env python
"""
Demonstrate how to do two plots on the same axes with different left
right scales.
The trick is to use *2 different axes*. Turn the axes rectangular
frame off on the 2nd axes to keep it from obscuring the first.
Manually set the tick locs and labels as desired. You can use
separate matplotlib.ticker formatters and locators as desired since
the two axes are independent.
This is acheived in the following example by calling pylab's twinx()
function, which performs this work. See the source of twinx() in
pylab.py for an example of how to do it for different x scales. (Hint:
use the xaxis instance and call tick_bottom and tick_top in place of
tick_left and tick_right.)
"""
from pylab import *
ax1 = subplot(111)
t = arange(0.01, 10.0, 0.01)
s1 = exp(t)
plot(t, s1, 'b-')
xlabel('time (s)')
ylabel('exp')
# turn off the 2nd axes rectangle with frameon kwarg
ax2 = twinx()
s2 = sin(2*pi*t)
plot(t, s2, 'r.')
ylabel('sin')
ax2.yaxis.tick_right()
show()
#!/usr/bin/env python
"""
The default drawing order for axes is patches, lines, text. This
order is determined by the zorder attribute. The following defaults
are set
Artist Z-order
Patch / PatchCollection 1
Line2D / LineCollection 2
Text 3
You can change the order for individual artists by setting the zorder. Any
individual plot() call can set a value for the zorder of that particular item.
In the fist subplot below, the lines are drawn above the patch
collection from the scatter, which is the default.
In the subplot below, the order is reversed.
The second figure shows how to control the zorder of individual lines.
"""
from pylab import *
x = rand(20); y = rand(20)
subplot(211)
plot(x, y, 'r', lw=3)
scatter(x,y,s=120)
subplot(212)
plot(x, y, 'r', zorder=1, lw=3)
scatter(x,y,s=120, zorder=2)
# A new figure, with individually ordered items
x=frange(0,2*pi,npts=100)
figure()
plot(x,sin(x),linewidth=10, color='black',label='zorder=10',zorder = 10) # on top
plot(x,cos(1.3*x),linewidth=10, color='red', label='zorder=1',zorder = 1) # bottom
plot(x,sin(2.1*x),linewidth=10, color='green', label='zorder=3',zorder = 3)
axhline(0,linewidth=10, color='blue', label='zorder=2',zorder = 2)
l = legend()
l.set_zorder(20) # put the legend on top
show()