matplotlib

Get axes mosaic label after passed into function?


I want the mosaic layout label of an axes after axes has been passed into a function.

Simplified example:

def test_function(ax):
    print(ax)

mosaic_subplot_layout = {'axes': [['boxplot'], ['histogram'], ['histogram'], ['histogram']]}
my_figure = plt.figure()
ax_dict = my_figure.subplot_mosaic(mosaic_subplot_layout['axes'])
for axes in ax_dict:
    test_function(ax=ax_dict[axes])

Returns:

Axes(0.125,0.712609;0.775x0.167391)
Axes(0.125,0.11;0.775x0.56913)

Desired:

boxplot
histogram

Googling this all I've found are tips on how to change tick labels or other labels, not helpful. The way I've found to do this is like so:

def test_function(ax):
    print(ax)
mosaic_subplot_layout = {'axes': [['boxplot'], ['histogram'], ['histogram'], ['histogram']]}
my_figure = plt.figure()
ax_dict = my_figure.subplot_mosaic(mosaic_subplot_layout['axes'])
for axes in ax_dict:
    test_function(ax=axes)

But this creates other problems in my real code and isn't desirable.

What should I try next?


Solution

  • Each artist can have a label and the mosaic labels are used as Axes labels when internally adding the subplots. So it's simply

    def test_function(ax):
        print(ax.get_label())
    

    Example (your example mosaic has only 2 Axes due to repeating dict keys):

    mosaic_subplot_layout = {'axes': [['boxplot'], ['histogram'], ['barplot'], ['image']]}
    my_figure = plt.figure()
    ax_dict = my_figure.subplot_mosaic(mosaic_subplot_layout['axes'])
    for axes in ax_dict:
        test_function(ax=ax_dict[axes])
    

    Output:

    boxplot
    histogram
    barplot
    image