Search code examples
pythonmatplotlib

Matplotlib make axes locatable align labels


I am using make_axes_locatable to create a plot of this layout: layout of my plot

As you can see, the axis labels are not aligned. My code looks like this:

import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable

fig, ax = plt.subplots()
plt.tight_layout()
ax.set_aspect("equal")
divider = make_axes_locatable(ax)

ax_histx = divider.append_axes("top", size="25%", pad="0.75%", sharex=ax)
ax_histy = divider.append_axes("right", size="25%", pad="0.75%", sharey=ax)
cax = divider.append_axes("right", size="4%", pad="0.75%")
hcax = divider.append_axes("top", size="4%", pad="0.75%")

ax.set_xlim(0,10000)
ax.set_ylim(0,10000)
ax.tick_params(axis='x', rotation=90)

ax.set_xlabel("xlabel")
ax_histy.set_xlabel("xlabel")
ax.set_ylabel("ylabel")
ax_histx.set_ylabel("ylabel")

fig.align_labels()

plt.show()

I added fig.align_labels() to my code, but that didn't help. The versions for just the x or y axes don't work either. I am using matplotlib 3.6.0


Solution

  • align_labels only works for labels in the same GridSpec, but the axes added by divider have no GridSpec.

    I don't know of any documented way of aligning the labels in this case, but you could use the internal and undocumented label groupers by adding these two lines after setting the labels:

    fig._align_label_groups['x'].join(ax, ax_histy)
    fig._align_label_groups['y'].join(ax, ax_histx)
    

    enter image description here