Phython and graphing

John Hunter jdhunter at ace.bsd.uchicago.edu
Fri Apr 21 00:26:26 EDT 2006


>>>>> "mostro" == mostro  <Adisegna at gmail.com> writes:

    mostro> Hello, Can someone lead me to an easy way to create a
    mostro> graph in Python.

    mostro> For example, I have a script running that creates a list
    mostro> of dates, times and values. I would like to turn this into
    mostro> a graph.

    mostro> I can grep the info into a new file creating two columns
    mostro> (x,y) but the issue is the graph.

    mostro> P.S. I'm a Python newbie so keep that in mind.

Here's an example from the matplotlib examples dir

  http://matplotlib.sf.net/examples

that does just that.  It loads dates and values from a file using the
load function, and then plots them with the plot_date command

The delimiter directive in the load command says to use comma
separated values.  The converters arg is a dictionary mapping column
number to a function that converts that column to a float (datestr2num
converts date strings to matplotlib dates using the wonderful
dateutil.parser.parse function that can convert just about any date
string -- the default column converter is 'float').  skiprows
indicates that there is a single line of header to convert, and
usecols says to take the first and third columns.

The rest is easy -- just call plot_dates:

from pylab import figure, show, datestr2num, load
dates, closes = load(
    'data/msft.csv', delimiter=',',
    converters={0:datestr2num}, skiprows=1, usecols=(0,2),
    unpack=True)

fig = figure()
ax = fig.add_subplot(111)
ax.plot_date(dates, closes)
show()


Here is a brief look at the data file being plotted:

Date,Open,High,Low,Close,Volume,Adj. Close*
19-Sep-03,29.76,29.97,29.52,29.96,92433800,29.79
18-Sep-03,28.49,29.51,28.42,29.50,67268096,29.34
17-Sep-03,28.76,28.95,28.47,28.50,47221600,28.34
16-Sep-03,28.41,28.95,28.32,28.90,52060600,28.74
15-Sep-03,28.37,28.61,28.33,28.36,41432300,28.20
.... and many more


JDH



More information about the Python-list mailing list