I have a pb with the tick's labels alignment of an imshow figure. I would like to center the labels between two Y-ticks but I do not succeed. I know that we can find numerous examples (including in StackOverflow), but I did not find what I was looking for.
import datetime
dateFMT = '%Y-%m-%d %H:%M:%S'
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# Fontsize
ftsize = 12
# - Months in French
tabMois=['Janvier','Fevrier','Mars','Avril','Mai','Juin','Juillet','Aout','Septembre',
'Octobre','Novembre','Decembre']
# - Nb of Days of Measurements
NbOfDays = 7.99
# - Generating a DateTimeIndex from January the 1st and during ~8 days
start = datetime.datetime.strptime('2020-01-01 00:00:00', dateFMT)
end = start + datetime.timedelta(days=NbOfDays)
times = pd.date_range(freq='60Min', start=start, end=end)
# - Total number of values
NbOfDates = len (times)
# - Creating the dataframe with random values
df = pd.DataFrame(np.random.randint(0,4,size=(NbOfDates, 1)),
columns=['Temperature'], index=times)
# - Creating 2 columns for referencing dates and hours
date = [d.strftime('%d/%m') for d in df.index]
df['jour'] = date
heure = [d.strftime('%H') for d in df.index]
df['heure'] = heure
# - Creating a new DataFrame (dfPivot) containing the matrix of the previous
# Dataframe
dfPivot = df.pivot(index='jour', columns='heure', values='Temperature')
# - X Labels for the plot
XTicksLabels = [ str(i)+'h' for i in dfPivot.columns ]
# - Small function to split days and monthes and to translate in French
def splitDate( i ):
day = i.split('/')[0]
month = int(i.split('/')[1])
monthInFrench = tabMois[month-1]
label = str(day)+' '+monthInFrench
return label
# - Y Labels for the plot
YTicksLabels = [ splitDate( i ) for i in dfPivot.index ]
# - Plot
fig, ax = plt.subplots()
im = ax.imshow(dfPivot, aspect = 'auto', interpolation='None')
ax.xaxis.set(ticks=np.arange(0.5, len(XTicksLabels)), ticklabels=XTicksLabels)
ax.set_xticklabels(XTicksLabels, rotation=90, ha='right', minor=False)
ax.yaxis.set(ticks=np.arange(0.5, len(YTicksLabels)), ticklabels=YTicksLabels)
ax.set_yticklabels(YTicksLabels, rotation=0, ha='right', va = 'baseline',
minor=False, fontsize=ftsize)
ax.tick_params('y', length=10)
fig.colorbar(im)
plt.ylabel('Jours', size=ftsize)
plt.xlabel('Heures', size=ftsize)
plt.tight_layout()
plt.show()
The image produced by the code.