1

I have a pivot table created according to this: Color mapping of data on a date vs time plot and plot it with imshow(). I want to use the index and columns of the pivot table as yticks and xticks. The columns in my pivot table are dates and the index are time of the day.

data = pd.DataFrame()
data['Date']=Tgrad_GFAVD_3m2mRot.index.date
data['Time']=Tgrad_GFAVD_3m2mRot.index.strftime("%H")
data['Tgrad']=Tgrad_GFAVD_3m2mRot.values

C = data.pivot(index='Time', columns='Date', values='Tgrad')

print(C.head()):

Date  2016-08-01  2016-08-02  2016-08-03  2016-08-04  2016-08-05  2016-08-06  \
Time                                                                           
00     -0.841203   -0.541871   -0.042984   -0.867929   -0.790869   -0.940757   
01     -0.629176   -0.520935   -0.194655   -0.866815   -0.794878   -0.910690   
02     -0.623608   -0.268820   -0.255457   -0.859688   -0.824276   -0.913808   
03     -0.615145   -0.008241   -0.463920   -0.909354   -0.811136   -0.878619   
04     -0.726949   -0.169488   -0.529621   -0.897773   -0.833408   -0.825612  

I plot the pivot table with

fig, ax = plt.subplots(figsize = (16,9))
plt = ax.imshow(C,aspect = 'auto', extent=[0,len(data["Date"]),0,23], origin = "lower")   

I tried a couple of things but nothing worked. At the moment my xticks range between 0 and 6552, which is the length of the C.columns object and is set by the extent argument in imshow()

I would like to have the xticks at every first of the month but not by index number but as a datetick in the format "2016-08-01" for example.

I am sure it was just a small thing that has been stopping me the last hour, but now I give up. Do you know how to set the xticks accordingly?

Vroni
  • 347
  • 1
  • 5
  • 16

1 Answers1

0

I found the solution myself after trying one more thing.. I created another column in the "data" Dataframe with datenum entries instead of dates

data["datenum"]=mdates.date2num(data["Date"])

Then changed the plot line to:

pl = ax.imshow(C,aspect = 'auto',
           extent=[data["datenum"].iloc[0],data["datenum"].iloc[-1],data["Time"].iloc[0],data["Time"].iloc[-1]],
           origin = "lower")

So the change of the extent argument provided the datenum values to the plot instead of the index of the date column. Then with this the following lines worked:

ax.set_yticks(data["Time"]) # sets yticks
ax.xaxis_date() # tells the xaxis that it should expect datetime values
ax.xaxis.set_major_formatter(mdates.DateFormatter("%m/%d") ) # formats the datetime values
fig.autofmt_xdate() # makes it look nice

Best, Vroni

Vroni
  • 347
  • 1
  • 5
  • 16