Skip to content

Commit f816461

Browse files
committed
added file plotting function
svn path=/trunk/matplotlib/; revision=3374
1 parent 8dcfdac commit f816461

File tree

4 files changed

+147
-8
lines changed

4 files changed

+147
-8
lines changed

CHANGELOG

+3
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
2007-06-08 Added gnuplot file plotfile function to pylab -- see
2+
examples/plotfile_demo.py - JDH
3+
14
2007-06-07 Disable build of numarray and Numeric extensions for
25
internal MPL use and the numerix layer. - ADS
36

examples/plotfile_demo.py

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
from pylab import plotfile, show
2+
3+
fname = 'data/msft.csv'
4+
5+
# test 1; use ints
6+
plotfile(fname, (0,5,6))
7+
8+
# test 2; use names
9+
plotfile(fname, ('date', 'volume', 'adj_close'))
10+
11+
# test 3; use semilogy for volume
12+
plotfile(fname, ('date', 'volume', 'adj_close'), plotfuncs={'volume': 'semilogy'})
13+
14+
# test 4; use semilogy for volume
15+
plotfile(fname, (0,5,6), plotfuncs={5:'semilogy'})
16+
17+
# test 5; use bar for volume
18+
plotfile(fname, (0,5,6), plotfuncs={5:'bar'})
19+
20+
show()
21+
22+

lib/matplotlib/mlab.py

+18-8
Original file line numberDiff line numberDiff line change
@@ -1358,7 +1358,7 @@ def load(fname,comments='#',delimiter=None, converters=None,skiprows=0,
13581358
if unpack: return transpose(X)
13591359
else: return X
13601360

1361-
def csv2rec(fname, comments='#', skiprows=0, checkrows=1):
1361+
def csv2rec(fname, comments='#', skiprows=0, checkrows=5, delimiter=','):
13621362
"""
13631363
Load ASCII data from fname into a numpy recarray and return the
13641364
numpy recarray.
@@ -1389,7 +1389,7 @@ def csv2rec(fname, comments='#', skiprows=0, checkrows=1):
13891389

13901390

13911391
fh = to_filehandle(fname)
1392-
reader = csv.reader(fh)
1392+
reader = csv.reader(fh, delimiter=delimiter)
13931393

13941394
def process_skiprows(reader):
13951395
if skiprows:
@@ -1399,18 +1399,23 @@ def process_skiprows(reader):
13991399
return fh, reader
14001400

14011401
process_skiprows(reader)
1402-
1402+
1403+
1404+
14031405
def get_func(item, func):
14041406
# promote functions in this order
1405-
funcmap = {None:int, int:float, float:parsedate, parsedate:str}
1407+
funcmap = {int:float, float:dateutil.parser.parse, dateutil.parser.parse:str}
14061408
try: func(item)
1407-
except: return funcmap[func]
1408-
else: return func
1409-
1409+
except:
1410+
if func==str:
1411+
raise ValueError('Could not find a working conversion function')
1412+
else: return get_func(item, funcmap[func]) # recurse
1413+
else: return func
14101414

14111415

14121416
def get_converters(reader):
14131417

1418+
converters = None
14141419
for i, row in enumerate(reader):
14151420
if i==0:
14161421
converters = [int]*len(row)
@@ -1429,14 +1434,19 @@ def get_converters(reader):
14291434
delete.add('"')
14301435

14311436
names = []
1437+
14321438
for i, item in enumerate(header):
14331439
item = item.strip().lower().replace(' ', '_')
14341440
item = ''.join([c for c in item if c not in delete])
1441+
if not len(item):
1442+
item = 'column%d'%i
14351443
names.append(item)
14361444

14371445
# get the converter functions by inspecting checkrows
14381446
converters = get_converters(reader)
1439-
1447+
if converters is None:
1448+
raise ValueError('Could not find any valid data in CSV file')
1449+
14401450
# reset the reader and start over
14411451
fh.seek(0)
14421452
process_skiprows(reader)

lib/matplotlib/pylab.py

+104
Original file line numberDiff line numberDiff line change
@@ -213,6 +213,11 @@
213213
from artist import getp, get
214214
from artist import setp as _setp
215215

216+
217+
218+
import matplotlib.cbook as cbook
219+
from matplotlib.mlab import csv2rec
220+
216221
# a hack to keep old versions of ipython working with mpl after bug
217222
# fix #1209354
218223
if 'IPython.Shell' in sys.modules:
@@ -1500,6 +1505,103 @@ def box(on=None):
15001505
ax.set_frame_on(on)
15011506
draw_if_interactive()
15021507

1508+
1509+
1510+
1511+
def plotfile(fname, cols=(0,), plotfuncs=None,
1512+
comments='#', skiprows=0, checkrows=5, delimiter=',',
1513+
**kwargs):
1514+
"""
1515+
plot the data in fname
1516+
1517+
cols is a sequence of column identifiers to plot. An identifier
1518+
is either an int or a string. if it is an int, it indicates the
1519+
column number. If it is a string, it indicates the column header.
1520+
mpl will make column headers lower case, replace spaces with
1521+
strings, and remove all illegal characters; so 'Adj Close*' will
1522+
have name 'adj_close'
1523+
1524+
if len(cols)==1, only that column will be plotted on the y axis.
1525+
if len(cols)>1, the first element will be an identifier for data
1526+
for the x axis and the remaining elements will be the column
1527+
indexes for multiple subplots
1528+
1529+
plotfuncs, if not None, is a dictionary mapping identifier to an
1530+
Axes plotting function as a string. Default is 'plot', other
1531+
choices are 'semilogy', 'fill', 'bar', etc... You must use the
1532+
same type of identifier in the cols vector as you use in the
1533+
plotfuncs dictionary, eg integer column numbers in both or column
1534+
names in both.
1535+
1536+
comments, skiprows, checkrows, and delimiter are all passed on to
1537+
matplotlib.mlab.csv2rec to load the data into a record array
1538+
1539+
kwargs are passed on to plotting functions
1540+
1541+
Example usage:
1542+
1543+
# plot the 2nd and 4th column against the 1st in two subplots
1544+
plotfile(fname, (0,1,3))
1545+
1546+
# plot using column names; specify an alternate plot type for volume
1547+
plotfile(fname, ('date', 'volume', 'adj_close'), plotfuncs={'volume': 'semilogy'})
1548+
"""
1549+
1550+
fig = figure()
1551+
if len(cols)<1:
1552+
raise ValueError('must have at least one column of data')
1553+
1554+
if plotfuncs is None:
1555+
plotfuncs = dict()
1556+
r = csv2rec(fname, comments=comments,
1557+
skiprows=skiprows, checkrows=checkrows, delimiter=delimiter)
1558+
1559+
def getname_val(identifier):
1560+
'return the name and column data for identifier'
1561+
if cbook.is_string_like(identifier):
1562+
return identifier, r[identifier]
1563+
elif cbook.is_numlike(identifier):
1564+
name = r.dtype.names[int(identifier)]
1565+
return name, r[name]
1566+
1567+
1568+
xname, x = getname_val(cols[0])
1569+
1570+
if len(cols)==1:
1571+
ax1 = fig.add_subplot(N,1,i)
1572+
funcname = plotfuncs.get(cols[0], 'plot')
1573+
func = getattr(ax1, funcname)
1574+
func(x, **kwargs)
1575+
ax1.set_xlabel(xname)
1576+
else:
1577+
N = len(cols)
1578+
for i in range(1,N):
1579+
if i==1:
1580+
ax = ax1 = fig.add_subplot(N-1,1,i)
1581+
ax.grid(True)
1582+
else:
1583+
ax = fig.add_subplot(N-1,1,i, sharex=ax1)
1584+
ax.grid(True)
1585+
1586+
1587+
yname, y = getname_val(cols[i])
1588+
1589+
funcname = plotfuncs.get(cols[i], 'plot')
1590+
func = getattr(ax, funcname)
1591+
1592+
func(x, y, **kwargs)
1593+
ax.set_ylabel(yname)
1594+
if ax.is_last_row():
1595+
ax.set_xlabel(xname)
1596+
else:
1597+
ax.set_xlabel('')
1598+
1599+
1600+
if xname=='date':
1601+
fig.autofmt_xdate()
1602+
1603+
1604+
15031605
### Deprecated functions:
15041606
def scatter_classic(*args, **kwargs):
15051607
return gca().scatter_classic(*args, **kwargs)
@@ -1511,6 +1613,8 @@ def pcolor_classic(*args, **kwargs):
15111613
if Axes.pcolor_classic.__doc__ is not None:
15121614
pcolor_classic.__doc__ = dedent(Axes.pcolor_classic.__doc__)
15131615

1616+
1617+
15141618
### Do not edit below this point
15151619
# This function was autogenerated by boilerplate.py. Do not edit as
15161620
# changes will be lost

0 commit comments

Comments
 (0)