title: Manually setting xticks with xaxis_date() in Python/matplotlib
body: <p>I've been looking into how to make plots against time on the x axis and have it pretty much sorted, with one strange quirk that makes me wonder whether I've run into a bug or (admittedly much more likely) am doing something I don't really understand.</p>
  
  <p>Simply put, below is a simplified version of my program. If I put this in a .py file and execute it from an interpreter (ipython) I get a figure with an x axis with the year only, "2012", repeated a number of times, <a href="http://30.media.tumblr.com/tumblr_m0p1j2eay51rry1owo1_500.png" rel="nofollow">like this</a>.</p>
  
  <p>However, if I comment out the line (40) that sets the xticks manually, namely 'plt.xticks(tk)' and then run that exact command in the interpreter immediately after executing the script, it works great and my figure looks <a href="http://27.media.tumblr.com/tumblr_m0p1j2eay51rry1owo2_500.png" rel="nofollow">like this</a>.</p>
  
  <p>Similarly it also works if I just move that line to be after the savefig command in the script, that's to say to put it at the very end of the file. Of course in both cases only the figure drawn on screen will have the desired axis, and not the saved file. Why can't I set my x axis earlier? </p>
  
  <p>Grateful for any insights, thanks in advance!</p>
  
  <pre><code>import matplotlib.pyplot as plt 
  import datetime
  
  # define arrays for x, y and errors
  x=[16.7,16.8,17.1,17.4]
  y=[15,17,14,16]
  e=[0.8,1.2,1.1,0.9]
  
  xtn=[]
  
  # convert x to datetime format
  for t in x:
     hours=int(t)
     mins=int((t-int(t))*60)
     secs=int(((t-hours)*60-mins)*60)
     dt=datetime.datetime(2012,01,01,hours,mins,secs)
     xtn.append(date2num(dt))
  
  # set up plot
  fig=plt.figure()
  ax=fig.add_subplot(1,1,1)
  
  # plot
  ax.errorbar(xtn,y,yerr=e,fmt='+',elinewidth=2,capsize=0,color='k',ecolor='k')
  
  # set x axis range
  ax.xaxis_date()
  t0=date2num(datetime.datetime(2012,01,01,16,35)) # x axis startpoint
  t1=date2num(datetime.datetime(2012,01,01,17,35)) # x axis endpoint
  plt.xlim(t0,t1) 
  
  # manually set xtick values 
  tk=[]
  tk.append(date2num(datetime.datetime(2012,01,01,16,40)))
  tk.append(date2num(datetime.datetime(2012,01,01,16,50)))
  tk.append(date2num(datetime.datetime(2012,01,01,17,00)))
  tk.append(date2num(datetime.datetime(2012,01,01,17,10)))
  tk.append(date2num(datetime.datetime(2012,01,01,17,20)))
  tk.append(date2num(datetime.datetime(2012,01,01,17,30)))
  plt.xticks(tk)
  
  plt.show()
  
  # save to file
  plt.savefig('savefile.png')
  </code></pre>