Matplotlib - Setting a tick label's background colour

I have a subplot and its tick labels overlap with the data. I would like to set the x-tick labels to have a background colour (e.g. white). Currently I have only been able to find how to change the label's colour, but not the background. I know how to get the effect using a text object as shown below. (NB - I don't want the whole subplot's margin to be coloured, but just the tick label).


enter image description here

import matplotlib as mpl

rc_fonts = {
    "text.usetex": True,
    'text.latex.preview': True,
    "font.size": 50,
    'mathtext.default': 'regular',
    'axes.titlesize': 55,
    "axes.labelsize": 55,
    "legend.fontsize": 50,
    "xtick.labelsize": 50,
    "ytick.labelsize": 50,
    'figure.titlesize': 55,
    'figure.figsize': (10, 6.5),  # 15, 9.3
    'text.latex.preamble': [
    "": "serif",
    "font.serif": "computer modern roman",
import matplotlib.pylab as plt
from mpl_toolkits.axes_grid1.inset_locator import inset_axes, InsetPosition, mark_inset
from numpy import linspace, sin

x = linspace(0, 1, 100)
ax1 = plt.gca()
ax2 = plt.axes([0, 0, 1, 1], label=str(2))
ip = InsetPosition(ax1, [0.08, 0.63, 0.45, 0.3])
ax1.plot(x, x)
ax1.plot(x, x + 0.3)
ax1.set_xlim(0, 1)
ax1.set_ylim(0, 1)
ax1.text(0.3, 0.3, '$1$', transform=ax1.transAxes, horizontalalignment='center', verticalalignment='center', color='black', backgroundcolor='white')


enter image description here

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots()

ax.plot(np.linspace(0, 1, 5), np.random.rand(5))

# set xticklabels
xtl = []
for x in ax.get_xticks():
    xtl += ['lbl: {:.1f}'.format(x)]

# modify labels
for tl in ax.get_xticklabels():
    txt = tl.get_text()
    if txt == 'lbl: 1.0':
        txt += ' (!)'
Posted on by Markus Dutschke

To set a label's background color you may use the same property as for a text, essentially because a label is a text.

plt.setp(ax2.get_xticklabels(), backgroundcolor="limegreen")

enter image description here

For more sophisticated backgrounds, you could also use the bbox property.

bbox = dict(boxstyle="round", ec="limegreen", fc="limegreen", alpha=0.5)
plt.setp(ax2.get_xticklabels(), bbox=bbox)

enter image description here

Posted on by ImportanceOfBeingErnest

Relevant tags