mhdadk
mhdadk

Reputation: 865

How can I add "secondary" labels with different font sizes to axes in Matplotlib?

I am trying to generate the following figure in Matplotlib:

enter image description here

Code used to generate the axes (without the labels):

import matplotlib.pyplot as plt
fig,ax = plt.subplots(3,3,sharex=True,sharey=True,
                      constrained_layout=False)

I know how to add the labels "X-axis label here" and "Y-axis label here", but I am not sure how to place the labels "A","B","C","D","E", and "F" where they are shown in the figure above. These labels should also have different font sizes to "X-axis label here" and "Y-axis label here". Any suggestions?

Upvotes: 1

Views: 703

Answers (1)

Mr. T
Mr. T

Reputation: 12410

The general approach would be to use ax.annotate() but for the x-axis, we can simply use the subplot title:

import matplotlib.pyplot as plt
fig, ax = plt.subplots(3,3,sharex=True,sharey=True,
                      constrained_layout=False, figsize=(10, 6))

x_titles = list("DEF")
y_titles = list("ABC")
for curr_title, curr_ax in zip(x_titles, ax[0, :]):
    curr_ax.set_title(curr_title, fontsize=15)
for curr_title, curr_ax in zip(y_titles, ax[:, 0]):
    #the xy coordinates are in % axes from the lower left corner (0,0) to the upper right corner (1,1)
    #the xytext coordinates are offsets in pixel to prevent 
    #that the text moves in relation to the axis when resizing the window
    curr_ax.annotate(curr_title, xy=(0, 0.5), xycoords="axes fraction", 
                     xytext=(-80, 0), textcoords='offset pixels',
                     fontsize=15, rotation="vertical")
plt.show()

Sample output: enter image description here

Upvotes: 2

Related Questions