Matplotlib-设置刻度标签的背景色

时间:2018-11-22 14:38:52

标签: matplotlib colors

我有一个子图,它的刻度标签与数据重叠。 我想将x-tick标签设置为背景颜色(例如白色)。目前,我只能找到如何更改标签的颜色,而不能找到背景。我知道如何使用文本对象获得效果,如下所示。 (注意-我不希望整个子图的边距被着色,而只是勾号标签。)

MWE

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': [
        r"""\usepackage{lmodern,amsmath,amssymb,bm,physics,mathtools,nicefrac,letltxmacro,fixcmex}
        """],
    "font.family": "serif",
    "font.serif": "computer modern roman",
}
mpl.rcParams.update(rc_fonts)
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)
plt.clf()
ax1 = plt.gca()
ax2 = plt.axes([0, 0, 1, 1], label=str(2))
ip = InsetPosition(ax1, [0.08, 0.63, 0.45, 0.3])
ax2.set_axes_locator(ip)
ax1.plot(x, x)
ax1.plot(x, x + 0.3)
ax1.set_xlim(0, 1)
ax1.set_ylim(0, 1)
ax2.xaxis.set_tick_params(labelcolor='r')
ax1.text(0.3, 0.3, '$1$', transform=ax1.transAxes, horizontalalignment='center', verticalalignment='center', color='black', backgroundcolor='white')

2 个答案:

答案 0 :(得分:4)

要设置标签的背景色,可以使用与文本相同的属性,主要是因为标签是文本。

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

enter image description here

对于更复杂的背景,您还可以使用bbox属性。

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

enter image description here

答案 1 :(得分:2)

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)]
ax.set_xticklabels(xtl)

# modify labels
for tl in ax.get_xticklabels():
    txt = tl.get_text()
    if txt == 'lbl: 1.0':
        txt += ' (!)'
        tl.set_backgroundcolor('C3')
    tl.set_text(txt)