Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 967cb70

Browse files
committed
adding examples
svn path=/trunk/matplotlib/; revision=8
1 parent 48111d0 commit 967cb70

19 files changed

Lines changed: 542 additions & 0 deletions

examples/README

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
Here are some demos of how to use the matplotlib.
2+
3+
4+
-- data_helper.py - a convenience module to load some data from the
5+
data dir
6+
7+
-- embedding_in_gtk - The Figure class derives from gtk.DrawingArea,
8+
so it is easy to embed in larger applications.
9+
10+
-- histograms_gauss.py - 2D histograms; requires the jdh.mlab module
11+
12+
-- simple_plot.py - the basic 2D line plot
13+
14+
-- subplot_demo.py - how to do multiple axes on a single plot
15+
16+
-- vline_demo.py - working with straight lines
17+
18+
-- stock_demo.py - working with large datasets. Click on the plot and
19+
launch the navigation tool; wheel mouse over the navigation
20+
buttons to scroll and zoom. There are 58 days of minute by
21+
minute stock quotes for two tickers. The plot lib uses
22+
Numeric's super speedy searchsorted routine to extract the
23+
clipping indices so only the data in the viewport are handled.
24+

examples/__init__.py

Whitespace-only changes.

examples/axes_demo.py

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
# Demonstrate arbitrary placement of axes
2+
from matplotlib.matlab import *
3+
4+
dt = 0.001
5+
t = arange(0.0, 10.0, dt)
6+
r = exp(-t[:1000]/0.05) # impulse response
7+
x = randn(len(t))
8+
s = convolve(x,r,mode=2)*dt # colored noise
9+
s = s[:len(x)] # remove the decay tail which will skew
10+
# the probability distribution
11+
12+
# I'm just using the if 1 thing to break up the different regions of
13+
# the code visually.
14+
15+
# plot the noise
16+
if 1:
17+
plot(t, s)
18+
axis([0, 1, 1.1*min(s), 2*max(s) ])
19+
xlabel('time (s)')
20+
ylabel('current (nA)')
21+
22+
title('Gaussian white noise convolved with an exponential function')
23+
24+
# Make a histogram probability density inset
25+
if 1:
26+
a = axes([.65, .6, .2, .2], axisbg='y')
27+
n, bins, patches = hist(s, 400, normed=1)
28+
title('Probability')
29+
set(a, 'xticks', [])
30+
set(a, 'yticks', [])
31+
32+
# Make a histogram probability density inset
33+
if 1:
34+
a = axes([0.2, 0.6, .2, .2], axisbg='y')
35+
plot(t[:len(r)], r)
36+
title('Impulse response')
37+
set(a, 'xlim', [0,.2])
38+
set(a, 'xticks', [])
39+
set(a, 'yticks', [])
40+
41+
42+
show()

examples/data/AAPL.dat

251 KB
Binary file not shown.

examples/data/INTC.dat

310 KB
Binary file not shown.

examples/data_helper.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# Some functions to load a return data for the plot demos
2+
3+
from Numeric import fromstring, argsort, take
4+
import Numeric as numpy
5+
def get_two_stock_data():
6+
"""
7+
load stock time and price data for two stocks The return values
8+
(d1,p1,d2,p2) are the trade time (in days) and prices for stocks 1
9+
and 2 (intc and aapl)
10+
"""
11+
ticker1, ticker2 = 'INTC', 'AAPL'
12+
M1 = fromstring( file('data/%s.dat' % ticker1, 'rb').read(), 'd')
13+
14+
M1 = M1.resize( (M1.shape[0]/2,2) )
15+
16+
M2 = fromstring( file('data/%s.dat' % ticker2, 'rb').read(), 'd')
17+
M2 = M2.resize( (M2.shape[0]/2,2) )
18+
19+
d1, p1 = M1[:,0], M1[:,1]
20+
d2, p2 = M2[:,0], M2[:,1]
21+
return (d1,p1,d2,p2)
22+

examples/embedding_in_gtk.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import matplotlib.figure as mpl
2+
import Numeric as numpy
3+
import gtk
4+
5+
win = gtk.Window()
6+
win.set_name("Embedding in GTK")
7+
win.connect("destroy", gtk.mainquit)
8+
win.set_border_width(5)
9+
10+
vbox = gtk.VBox(spacing=3)
11+
win.add(vbox)
12+
vbox.show()
13+
14+
f = mpl.Figure()
15+
a = mpl.Subplot(111)
16+
t = numpy.arange(0.0,3.0,0.01)
17+
s = numpy.sin(2*numpy.pi*t)
18+
19+
a.plot(t,s)
20+
f.add_axis(a)
21+
f.show()
22+
vbox.pack_start(f)
23+
24+
button = gtk.Button('Quit')
25+
button.connect('clicked', lambda b: gtk.mainquit())
26+
button.show()
27+
vbox.pack_start(button)
28+
29+
win.show()
30+
gtk.mainloop()

examples/errorbar_demo.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
from matplotlib.matlab import *
2+
3+
t = arange(0.1, 4, 0.1)
4+
s = exp(-t)
5+
e = 0.1*randn(len(s))
6+
7+
errorbar(t, s, e, fmt='o')
8+
xlabel('Distance (m)')
9+
ylabel('Height (m)')
10+
title('Mean an standard error as a function of distance')
11+
show()
12+

examples/histogram_demo.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
from matplotlib.matlab import *
2+
3+
mu, sigma = 100, 15
4+
x = mu + sigma*randn(10000)
5+
6+
# the histogram of the data
7+
n, bins, patches = hist(x, 150, normed=1)
8+
9+
# add a 'best fit' line
10+
y = normpdf( bins, mu, sigma)
11+
l = plot(bins, y, 'r--')
12+
set(l, 'linewidth', 2)
13+
set(gca(), 'xlim', [40, 160])
14+
15+
xlabel('Smarts')
16+
ylabel('Probability')
17+
title('Histogram of IQ: mu=100, sigma=15')
18+
19+
20+
#savefig('figures/histogram.png')
21+
show()

examples/interactive.py

Lines changed: 202 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,202 @@
1+
#!/usr/bin/env python
2+
"""
3+
Use GTK interactively from the prompt, by Brian McErlean and John Finlay
4+
From http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65109
5+
"""
6+
import __builtin__
7+
import __main__
8+
import codeop
9+
import keyword
10+
import os
11+
import re
12+
import readline
13+
import threading
14+
import traceback
15+
import signal
16+
import sys
17+
18+
import pygtk
19+
pygtk.require("2.0")
20+
import gtk
21+
22+
from matplotlib.cbook import wrap
23+
from matplotlib.matlab import *
24+
import matplotlib.matlab
25+
26+
def walk_class (klass):
27+
list = []
28+
for item in dir (klass.__class__):
29+
if item[0] != "_":
30+
list.append (item)
31+
32+
for base in klass.__class__.__bases__:
33+
list = list + walk_class (base())
34+
35+
return list
36+
37+
class Completer:
38+
def __init__ (self, lokals):
39+
self.locals = lokals
40+
41+
self.completions = keyword.kwlist + \
42+
__builtin__.__dict__.keys() + \
43+
__main__.__dict__.keys()
44+
def complete (self, text, state):
45+
if state == 0:
46+
if "." in text:
47+
self.matches = self.attr_matches (text)
48+
else:
49+
self.matches = self.global_matches (text)
50+
try:
51+
return self.matches[state]
52+
except IndexError:
53+
return None
54+
55+
def update (self, locs):
56+
self.locals = locs
57+
58+
for key in self.locals.keys ():
59+
if not key in self.completions:
60+
self.completions.append (key)
61+
62+
def global_matches (self, text):
63+
matches = []
64+
n = len (text)
65+
for word in self.completions:
66+
if word[:n] == text:
67+
matches.append (word)
68+
return matches
69+
70+
def attr_matches (self, text):
71+
m = re.match(r"(\w+(\.\w+)*)\.(\w*)", text)
72+
if not m:
73+
return
74+
expr, attr = m.group(1, 3)
75+
76+
obj = eval (expr, self.locals)
77+
if str (obj)[1:4] == "gtk":
78+
words = walk_class (obj)
79+
else:
80+
words = dir(eval(expr, self.locals))
81+
82+
matches = []
83+
n = len(attr)
84+
for word in words:
85+
if word[:n] == attr:
86+
matches.append ("%s.%s" % (expr, word))
87+
return matches
88+
89+
class GtkInterpreter (threading.Thread):
90+
"""Run a gtk mainloop() in a separate thread.
91+
Python commands can be passed to the thread where they will be executed.
92+
This is implemented by periodically checking for passed code using a
93+
GTK timeout callback.
94+
"""
95+
TIMEOUT = 100 # Millisecond interval between timeouts.
96+
97+
def __init__ (self):
98+
threading.Thread.__init__ (self)
99+
self.ready = threading.Condition ()
100+
self.globs = globals ()
101+
self.locs = locals ()
102+
self._kill = 0
103+
self.cmd = '' # Current code block
104+
self.new_cmd = None # Waiting line of code, or None if none waiting
105+
106+
self.completer = Completer (self.locs)
107+
readline.set_completer (self.completer.complete)
108+
readline.parse_and_bind ('tab: complete')
109+
110+
def run (self):
111+
gtk.timeout_add (self.TIMEOUT, self.code_exec)
112+
try:
113+
if gtk.gtk_version[0] == 2:
114+
gtk.threads_init()
115+
except:
116+
pass
117+
118+
gtk.mainloop ()
119+
120+
def code_exec (self):
121+
"""Execute waiting code. Called every timeout period."""
122+
self.ready.acquire ()
123+
if self._kill: gtk.mainquit ()
124+
if self.new_cmd != None:
125+
self.ready.notify ()
126+
self.cmd = self.cmd + self.new_cmd
127+
self.new_cmd = None
128+
try:
129+
tmp = self.cmd[:-1]
130+
code = codeop.compile_command (self.cmd[:-1])
131+
if code:
132+
self.cmd = ''
133+
#print 'Execing', tmp
134+
exec (code, self.globs, self.locs)
135+
self.completer.update (self.locs)
136+
except Exception:
137+
traceback.print_exc ()
138+
self.cmd = ''
139+
140+
self.ready.release()
141+
return 1
142+
143+
def feed (self, code):
144+
"""Feed a line of code to the thread.
145+
This function will block until the code checked by the GTK thread.
146+
Return true if executed the code.
147+
Returns false if deferring execution until complete block available.
148+
"""
149+
if (not code) or (code[-1]<>'\n'): code = code +'\n' # raw_input strips newline
150+
self.completer.update (self.locs)
151+
self.ready.acquire()
152+
self.new_cmd = code
153+
self.ready.wait () # Wait until processed in timeout interval
154+
self.ready.release ()
155+
156+
return not self.cmd
157+
158+
def kill (self):
159+
"""Kill the thread, returning when it has been shut down."""
160+
self.ready.acquire()
161+
self._kill=1
162+
self.ready.release()
163+
self.join()
164+
165+
# Read user input in a loop, and send each line to the interpreter thread.
166+
167+
def signal_handler (*args):
168+
print "SIGNAL:", args
169+
sys.exit()
170+
171+
if __name__=="__main__":
172+
signal.signal (signal.SIGINT, signal_handler)
173+
signal.signal (signal.SIGSEGV, signal_handler)
174+
175+
prompt = '>> '
176+
interpreter = GtkInterpreter ()
177+
interpreter.start ()
178+
interpreter.feed ("from matplotlib import matlab")
179+
interpreter.feed ("from matplotlib.matlab import *")
180+
interpreter.feed ("sys.path.append('.')")
181+
if len (sys.argv) > 1:
182+
for line in file(sys.argv[1], 'r'):
183+
print '>>', line.rstrip(),
184+
interpreter.feed(line)
185+
gcf().draw()
186+
print """Welcome to matplotlib.
187+
188+
help(matlab) -- shows a list of all matlab compatible commands provided
189+
help(plotting) -- shows a list of plot specific commands
190+
"""
191+
192+
matplotlib.matlab.interactive = 1
193+
194+
try:
195+
while 1:
196+
command = raw_input (prompt) + '\n' # raw_input strips newlines
197+
prompt = interpreter.feed (command) and '>> ' or '... '
198+
except (EOFError, KeyboardInterrupt): pass
199+
200+
interpreter.kill()
201+
print
202+

0 commit comments

Comments
 (0)