2

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.

enter image description here

William Miller
  • 9,839
  • 3
  • 25
  • 46

2 Answers2

2

Based on this answer, you should be able to use,

# Create offset transform by 5 points in y direction
dx = 0/72.; dy = 10/72. 
offset = matplotlib.transforms.ScaledTranslation(dx, dy, fig.dpi_scale_trans)

# apply offset transform to all x ticklabels.
for label in ax.yaxis.get_majorticklabels():
    label.set_transform(label.get_transform() + offset)

As a full example using your data,

import datetime
dateFMT = '%Y-%m-%d %H:%M:%S'
import pandas as pd
import numpy as np
import matplotlib.transforms
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)

# Create offset transform by 5 points in y direction
dx = 0/72.; dy = 10/72. 
offset = matplotlib.transforms.ScaledTranslation(dx, dy, fig.dpi_scale_trans)

# apply offset transform to all x ticklabels.
for label in ax.yaxis.get_majorticklabels():
    label.set_transform(label.get_transform() + offset)

plt.tight_layout()
plt.show()

which gives,

enter image description here

Ed Smith
  • 12,716
  • 2
  • 43
  • 55
0

Try it this way:

  • Move the ticklabels a little bit higher (e.g. 0.1).
  • Use the minor ticks to make the larger seperations between the days, place them at the position where the major ticks were before.
  • Remove the major tick marks by setting their length to zero.
ax.yaxis.set(ticks=np.arange(0.1, len(YTicksLabels)), ticklabels=YTicksLabels)
ax.set_yticks(ticks=np.arange(0.5, len(YTicksLabels)), minor=True)
ax.tick_params(axis='y', which='minor', length=10)
ax.tick_params(axis='y', which='major', length=0)
JohanC
  • 71,591
  • 8
  • 33
  • 66