I have a vector [1,2,3,4,5,6,7,8,9]
and a coloring scheme [0,1,1,1,1,1,0,1,1]
and I want to make a simple line plot with colors depending on the color scheme and with dates on the xaxis defined by the timestamp vector [ pd.Timestamp(i,1,1) for i in range(2000,2009)]
. This is a toy example. In my data which I can't show here this vector is loaded from somewhere and is in timestamp format.
I used the following answer to generate this code which makes my plot:
import numpy as np
import pylab as pl
from matplotlib import collections as mc
import matplotlib.dates as mdates
x = [1,2,3,4,5,6,7,8,9]
colors = [0,1,1,1,1,1,0,1,1]
segments = []
y = x
cols = np.zeros(shape=(len(colors),4))
index = 0
for x1, x2, y1,y2 in zip(x, x[1:], y, y[1:]):
if colors[index]==0:
cols[index] = tuple([1,0,0,1])
else:
cols[index] = tuple([0,1,0,1])
index += 1
segments.append([(x1, y1), (x2, y2)])
lc = mc.LineCollection(segments, colors=cols, linewidths=2)
fig, ax = pl.subplots()
ax.add_collection(lc)
ax.autoscale()
ax.margins(0.1)
ax.set_xticklabels([ pd.Timestamp(i,1,1) for i in range(2000,2009)])
fig.autofmt_xdate()
pl.show()
but I have a problem formatting the date on the x axis. Adding these two lines before pl.show()
ax.xaxis.set_major_locator(mdates.AutoDateLocator())
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y/%m/%d'))
results in ValueError: ordinal must be >= 1
. This doesn't usually happen when the x axis is initially set to be of some dates format, but here the construction is special because of the usage of ax.add_collection(lc)
.
Can you help me fix this?