Python Matplotlib - Howto make line graph

scogger1974
scogger1974 used Ask the Experts™
on
I have the attached code. I want to take load.csv and plot it to a line graph using matplotlib and python. The code attached isnt't working and I am looking for guidance. Any ideas?
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
import matplotlib.cbook as cbook
import matplotlib.ticker as ticker

datafile = open('load.csv')
print 'loading', datafile
r = mlab.csv2rec(datafile)

r.sort()
r = r[-30:]


fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(r.SERVER, r.LOAD, 'o-')
fig.autofmt_xdate()


N = len(r)
ind = np.arange(N)

def format_date(x, pos=None):
    thisind = np.clip(int(x+0.5), 0, N-1)
    return r.date[thisind].strftime('%Y-%m-%d')

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(ind, r.adj_close, 'o-')
ax.xaxis.set_major_formatter(ticker.FuncFormatter(format_date))
fig.autofmt_xdate()

plt.show()

Open in new window

load.csv
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
I have attached the working code and kept the original lines of code as comments so that you can review the changes.

Mainly:

1. You used SERVER and LOAD as headers, you should have used the lowercase server, load.
2. r.adj_close doesn't exist it will throw you an error, I suppose it is a leftover from boilerplate code what you wanted to use here was r.load
3. Also in the format_date function u use r.date where you actually want to use r.server

Cheers,

John
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
import matplotlib.cbook as cbook
import matplotlib.ticker as ticker

datafile = open('load.csv')
print 'loading', datafile
r = mlab.csv2rec(datafile)

r.sort()
r = r[-30:]

fig = plt.figure()
ax = fig.add_subplot(111)
#ax.plot(r.SERVER, r.LOAD, 'o-')
ax.plot(r.server, r.load, 'o-')
fig.autofmt_xdate()


N = len(r)
ind = np.arange(N)

def format_date(x, pos=None):
    thisind = np.clip(int(x+0.5), 0, N-1)
#   return r.date[thisind].strftime('%Y-%m-%d')
    return r.server[thisind].strftime('%Y-%m-%d')

fig = plt.figure()
ax = fig.add_subplot(111)
#ax.plot(ind, r.adj_close, 'o-')
ax.plot(ind, r.load, 'o-')
ax.xaxis.set_major_formatter(ticker.FuncFormatter(format_date))
fig.autofmt_xdate()

plt.show()

Open in new window

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial