Monday, September 12, 2016

Using plt.imshow to label timeseries data with matplotlib

Recently I've been trying to find the most effective way to color-code time series data using matplotlib.

For instance, if I have a raster plot like this:
...and I want to label it like this:
How?

After lots of failed attempts involving horrific for loops and ax.fill_between, ax.fill, and several other inferior solutions, I found a quick and easy fix:

After plotting your time series raster plot,

    Given: 
      - an array colors in (R, G, B) format (same length as your time series data)
      - nr_neurons is the number of axes (in this case, 4)
      - vspace is a float representing the space between each time axis
      - A timeline variable, tspace (created with np.linspace)


Note the parameter aspect='auto'. This makes sure the image takes the shape of your existing axis.