How do I manipulate datetime (tick labels and limits) on a plot axis in Python?
Question: I have a plot created within a for loop with a list of datetimes as the x
values. The x ticks are labeled as dates, but I would like to display the hour
(i.e. 6, 12, 18, 24 repeating). I would also like to set xlim to wider than
the dataset so all data points are within the axes (not on the edges). I would
post the figure, but this is my first question on stackoverflow, so that is
not allowed.


Answer: It's a touch confusing the first time you do it, but it's easiest to use
explicit formatters and locators for this. To keep the points from touching
the boundaries, use `ax.margins(pad)` or equivalently `plt.margins(pad)`.

    
    
    import pandas as pd
    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib.dates as mdates
    
    dates = pd.date_range('01/01/2014', '01/05/2014', freq='1H')
    y = np.random.random(dates.size)
    
    locator = mdates.HourLocator(range(0, 24, 6))
    formatter = mdates.DateFormatter('%H')
    
    fig, ax = plt.subplots()
    ax.plot(dates, y, 'ko')
    ax.margins(0.05) # Keep points from touching margin of plot
    
    ax.xaxis.set(major_formatter=formatter, major_locator=locator)
    
    plt.show()
    

![enter image description here](http://i.stack.imgur.com/NUx2x.png)

Or you might prefer the hours to be displayed more like this:

    
    
    import pandas as pd
    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib.dates as mdates
    
    dates = pd.date_range('01/01/2014', '01/05/2014', freq='1H')
    y = np.random.random(dates.size)
    
    locator = mdates.HourLocator(range(0, 24, 6))
    formatter = mdates.DateFormatter('%H:%M')
    
    fig, ax = plt.subplots()
    ax.plot(dates, y, 'ko')
    ax.margins(0.05) # Keep points from touching margin of plot
    
    ax.xaxis.set(major_formatter=formatter, major_locator=locator)
    fig.autofmt_xdate() # Quick way of rotating tick labels
    
    plt.show()
    

![enter image description here](http://i.stack.imgur.com/arA0L.png)

