Search code examples
pythondatepandasvincent

How to get vincent to display a pandas date/time axis correctly?


I have a pandas dataframe that I want to use in a vincent visualization. I can visualize the data, however, the X axis should be displayed as dates and instead the dates are just given an integer index of 500, 1000, 1500, etc.

The dataframe looks like this:

    weight      date
0   125.200000  2013-11-18

Truncated for brevity.

My vincent code in my ipython notebook:

chart = vincent.Line(df[['weight']])
chart.legend(title='weight')
chart.axis_titles(x='Date', y='Weight')
chart.display()

How can I tell vincent that my dataframe contains dates such that the X axis labels are just like the dataframe's dates above, i.e. 2013-11-18?


Solution

  • ok, so here's what I did. I ran into this problem before with matplotlib, and it was so painful that wrote a blog post about it (http://codrspace.com/szeitlin/biking-data-from-xml-to-plots-part-2/). Vincent is not exactly the same, but essentially you have to do 4 steps:

    1. convert your dates to datetime objects, if you haven't already

    df['date_objs'] = df['date'].apply(pandas.to_datetime)

    1. convert your datetime objects to whatever format you want.
    2. make your datetime objects into your index

      df.index = df.index.values.astype('M8[D]')

    3. tell vincent you want to plot your data (weight) as the y-axis. It will automatically use the index of your dataframe as the x-axis.

      chart = vincent.Line(plot[['weight']]) 
      chart.axis_titles(x='dates', y='weight') 
      chart.display()