Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib Gridspec "Cell" labels

Using GridSpec, I have a regular lattice of plots. Assume 3 x 3. All plot axis are turned off as I am interested in the shape of the plot, not the individual axis values.

What I would like to do, is label the x and y axis of the larger box. For example, in the 3 x 3 case above, the x-axis could be ['A', 'B', 'C'] and the y-axis could be [1,2,3].

Is it possible to get this labeling? How can I access the grid spec axis?

Not much in the GridSpec documentation unless I am missing an obvious method name.

Code example. Data is in a pandas dataframe - ignore the brute force extraction with nested loops...

    fig = plt.figure(figsize=(12,12))

    gs = gridspec.GridSpec(40, 19, wspace=0.0, hspace=0.0)

    for j in nseasons:
        t = tt[j]
        nlats = t.columns.levels[0]
        for idx, k in enumerate(nlats):
            diurnal = t[k].iloc[0]
            ax = plt.subplot(gs[j, idx])
            ax.plot(y, diurnal.values, 'b-')
            ax.set_xticks([])
            ax.set_yticks([])
            fig.add_subplot(ax)
            sys.stdout.write("Processed plot {}/{}\r".format(cplots, nplots))
            sys.stdout.flush()
            cplots += 1

    #Here the figures axis labels need to be set.
like image 632
Jzl5325 Avatar asked Oct 17 '25 12:10

Jzl5325


1 Answers

As mentioned in the comments, you can do this with xlabel and ylabel by only labeling axes on the left and bottom of the figure. Example below.

from matplotlib import pyplot as plt
import matplotlib.gridspec as gridspec

fig = plt.figure(figsize=(12,12))

rows = 40
cols = 19
gs = gridspec.GridSpec(rows, cols, wspace=0.0, hspace=0.0)

for i in range(rows):
    for j in range(cols):
        ax = plt.subplot(gs[i, j])
        ax.set_xticks([])
        ax.set_yticks([])

    # label y 
    if ax.is_first_col():
        ax.set_ylabel(i, fontsize = 9)

    # label x 
    if ax.is_last_row():
        ax.set_xlabel(j, fontsize = 9)

plt.show()

enter image description here

like image 102
Molly Avatar answered Oct 19 '25 00:10

Molly