Difference between ax.set_xlabel() and ax.xaxis.set_label() in MatplotLib 3.0.1

smwikipedia picture smwikipedia · Nov 15, 2018 · Viewed 10.5k times · Source

(This may be a naive question. Pardon me if so.)

I am using Python 3.7.1 and MatplotLib 3.0.1.

In below simple code, I used different ways to assign labels to axes. They seem to be equivalent from an OO perspective. But only the x axis label shows. Why?

import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

x = np.linspace(-2,2,60)
y = np.linspace(-2,2,60)

xx, yy = np.meshgrid(x,y)

z = xx**2 + yy**3

surf = ax.plot_surface(xx, yy, z, cmap="viridis")

ax.set_xlabel('x axis')      # <====== This works
ax.yaxis.set_label('y axis') # <====== This doesn't work
ax.zaxis.set_label('z axis') # <====== This doesn't work

In below image, you can see only the label x axis is shown.

enter image description here

ADD 1

According to here, it seems the matplotlib.axis.XAxis.set_label() approach should work.

In my case, the ax.xaxis is of type mpl_toolkits.mplot3d.axis3d.XAxis. It's a little different type. But I think it should work as well.

Answer

DavidG picture DavidG · Nov 15, 2018

Looking at the documentation you have shown for matplotlib.axis.XAxis.set_label() it appears this is to do with assigning a label to the axis itself for potential use in a legend (see @ImportanceOfBeingErnest's answer for more explanation)

In any case, the equivalent to ax.set_xlabel is matplotlib.axis.Axis.set_label_text

Therefore changing the code to:

ax.set_xlabel('x axis')     
ax.yaxis.set_label_text('y axis')
ax.zaxis.set_label_text('z axis')

Gives the desired output:

enter image description here