Skip to content Skip to sidebar Skip to footer

Is It Possible To Set Higher Z-index Of The Axis Labels?

In the following code labels of the axis get hidden behind the graph lines: import numpy as np import matplotlib.pyplot as plt X = np.linspace(-np.pi, np.pi, 256, endpoint=True) C

Solution 1:

There is an rcParameteraxes.axisbelow which steers exactly this behaviour:

axes.axisbelow: draw axis gridlines and ticks

  • below patches (True);
  • above patches but below lines ('line');
  • or above all (False)

If you set

plt.rcParams["axes.axisbelow"] = False

at the top of the script, gridlines and tick(label)s are drawn on top of everything else. The result would then look like

enter image description here

Solution 2:

Although Ernest's answer is very helpful, I find the rcParams interface a bit clunky. Luckily, you can set the axisbelow option directly on the axes with the set_axisbelow() method. Here's the patched version of your code.

import numpy as np
import matplotlib.pyplot as plt

X = np.linspace(-np.pi, np.pi, 256, endpoint=True)
C,S = np.cos(X), np.sin(X)

plt.plot(X,C)
plt.plot(X,S)

plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi],
           [r'$-\pi$', r'$-\pi/2$', r'$0$', r'$+\pi/2$', r'$+\pi$'])

plt.yticks([-1, 0, +1],
           [r'$-1$', r'$0$', r'$+1$'])

ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data',0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data',0))

ax.set_axisbelow(False)  # <-- addedfor label in ax.get_xticklabels() + ax.get_yticklabels():
    label.set_fontsize(14)
    label.set_bbox(dict(facecolor='white', edgecolor='None', alpha=0.75 ))

plt.show()

Now the plot looks like Nicolas P. Rougier's tutorial says it should:

fixed plot with white background for tick labels

Post a Comment for "Is It Possible To Set Higher Z-index Of The Axis Labels?"