Home > other >  matplotlib.pyplot: align axes labels when using a colorbar for each subplot
matplotlib.pyplot: align axes labels when using a colorbar for each subplot

Time:10-04

The Problem: I am using matplotlib to create a figure with multiple subplots. Each subplot has both x- and y-axis labels, and may also have its own colorbar.

By default, axis labels are placed next to the tick marks (Figure 1, left). However, I want the y-axis labels to vertically align (Figure 1, right). I am using fig.align_labels() to do this.

Figure 1: Figure 1

I want to include colorbars on each subplot (Figure 2, left). However, when I use fig.align_labels(), the axis labels are simply collapsed onto the same position (Figure 2, right).

Figure 2: Figure 2

The Question: How can we align the y-axis labels when colorbars are used?

import matplotlib.pyplot as plt
import matplotlib.ticker as mtick
import numpy as np

x = np.array(np.arange(5))
y = [np.random.uniform(0.5,2,5)*np.random.random(5) 100,   # <-- 'Long' tick labels
    np.random.uniform(0.5,2,5)*np.random.random(5) 100,    # <-- 'Long' tick labels
    np.random.uniform(0.5,2,5)*np.random.random(5),        # <-- 'Short' tick labels
    np.random.uniform(0.5,2,5)*np.random.random(5)]        # <-- 'Short' tick labels

fig = plt.figure()

for plotnum,yvals in enumerate(y):
    ax = fig.add_subplot(2,2,plotnum 1)
    sc = ax.scatter(x,yvals,c=yvals)
    fig.colorbar(sc, ax=ax)

    ax.set(ylabel=f'Y Values {plotnum}', xlabel=f'X Values {plotnum}')
    ax.yaxis.set_major_formatter(mtick.StrMethodFormatter('{x:,.1f}')) 

plt.tight_layout()
plt.subplots_adjust(wspace=0.8, hspace=0.6)
fig.align_labels()
plt.show()

CodePudding user response:

The most optimal way to handle this in your code is to add a line to the loop process.

fig = plt.figure()

for plotnum,yvals in enumerate(y):
    ax = fig.add_subplot(2,2,plotnum 1)
    sc = ax.scatter(x,yvals,c=yvals)
    fig.colorbar(sc, ax=ax)
    ax.yaxis.set_label_coords(-0.4, 0.5) # update
    ax.set_ylabel(f'Y Values {plotnum}')
    ax.set_xlabel(f'X Values {plotnum}')
    ax.yaxis.set_major_formatter(mtick.StrMethodFormatter('{x:,.1f}')) 

plt.tight_layout()
plt.subplots_adjust(wspace=0.8, hspace=0.6)
#fig.align_ylabels()

plt.show()

enter image description here

  • Related