0

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!

5
  • 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. Commented Nov 24, 2014 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. Commented Nov 24, 2014 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? Commented Nov 24, 2014 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. Commented Nov 24, 2014 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 Commented Nov 24, 2014 at 17:01

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.