Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

This is probably a very simple question, but I'm new to python and can't figure it out. I'm trying to use matplotlib within a user-defined function, but I'm getting an error message. Here's the code I'm using:

def CreateInterval(start,stop):
    interval=dates[(dates['Date']>=start)&(dates['Date']<=stop)]
    plt.bar(interval['Date'],interval['Trips'])
    plt.xlabel('Date')
    plt.ylabel('Number Trips')
    plt.title('Number of trips during the interval',start,stop)
    plt.show()

CreateInterval('2012-03-13','2012-04-13')

As you can see, this code takes a user defined slice of the "dates" dataframe (a pandas object) and attempts to graph it (with a bar indicating the number of trips for each day in the slice).

When I run this code, I get an empty plot space and an error message "key error: 0"

Is it possible to use matplotlib within a user function like this? If so, how?

*Also, I know there is another stackoverflow question with a similar title to mine, but I don't think it answers my question.

Thanks!

share|improve this question
    
You are trying to compare strings as dates. In order to compare dates like that they must be date objects, see the datetime module and pandas date/time functionality. Be aware that the column of the pandas dataframe must also be actual dates not just strings. –  Ajean Nov 24 '14 at 16:36
    
Thanks, but the "Dates" column in the pandas dataframe comprises timestamps. Interestingly enough, if I replace all the plot lines of code from the function with a single line saying only "print interval" then the function successfully prints the interval dataframe. So I don't think the string vs. dates issue is at play here, although I could still be wrong. –  user3786999 Nov 24 '14 at 16:40
    
Aha, it looks like pandas timestamps are smart enough to handle the string comparison ... whereas datetime is not (at least in python 2). You learn something new everyday. On another note, what is the purpose of the start,stop in your call to title? –  Ajean Nov 24 '14 at 16:48
    
If you want to format the start and stop into the string you should do so, otherwise they're trying to be string parameters for title. –  Ajean Nov 24 '14 at 16:52
    
Can you add sample code that generates dates? It's likely to be a problem with the input rather than the plotting, but it's hard to tell with only a snippet of code –  Mr E Nov 24 '14 at 17:01

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.