0

In the timeline plot I’m making, I want date tickers to show only specified dates. (In my example I show tickers for events ‘A’, but it can be any list on tickers). I found how to do it when x-axis data is numeric (upper subplot in my example), but this won’t work with timestamp date type (bottom plot).

    import pandas as pd
    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib.dates as mdates
    import matplotlib.ticker as ticker

    myData = pd.DataFrame({'date':['2019-01-15','2019-02-10','2019-03-20','2019-04-17','2019-05-23','2019-06-11'],'cnt':range(6),'event':['a','b','a','b','a','b']})
    myData['date'] = [pd.Timestamp(j) for j in myData['date']]

start = pd.Timestamp('2019-01-01')
stop = pd.Timestamp('2019-07-01')
inxa = myData.loc[myData['event'] == 'a'].index
inxb = myData.loc[myData['event'] == 'b'].index
# create two plots, one with 'cnt' as x-axis, the other 'dates' on x-axis.
fig, ax = plt.subplots(2,1,figsize=(16,9))
ax[0].plot((0,6),(0,0), 'k')
ax[1].plot((start, stop),(0,0))


for g in inxa:
    ax[0].plot((myData.loc[g,'cnt'],myData.loc[g,'cnt']),(0,1),c='r')
    ax[1].plot((myData.loc[g,'date'],myData.loc[g,'date']),(0,1),c='r')
for g in inxb:
    ax[0].plot((myData.loc[g,'cnt'],myData.loc[g,'cnt']),(0,2),c='b')
    ax[1].plot((myData.loc[g,'date'],myData.loc[g,'date']),(0,2),c='b')
xlist0 = myData.loc[myData['event']=='a','cnt']
xlist1 = myData.loc[myData['event']=='a','date']

ax[0].xaxis.set_major_locator(ticker.FixedLocator(xlist0))
# ax[1].xaxis.set_major_locator(**???**)

enter image description here

Pav El
  • 371
  • 2
  • 13
  • For `ax[1]` How many or Where do you want tick labels? I imagine there is a duplicate Q&A here on SO, just need to understand what you are trying to do. – wwii Nov 30 '19 at 20:44

1 Answers1

1

Couldn't find a sufficient duplicate, maybe I didn't look hard enough. There are a number of ways to do this:

Converting to numbers first or using the underlying values of a Pandas DateTime Series

xticks = [mdates.date2num(z) for z in xlist1]
# or
xticks = xlist1.values

and at least a couple ways to use it/them

ax[1].xaxis.set_major_locator(ticker.FixedLocator(xticks))
ax[1].xaxis.set_ticks(xticks)

Date tick labels
How to set the xticklabels for date in matplotlib
how to get ticks every hour?
...

wwii
  • 23,232
  • 7
  • 37
  • 77