I am having trouble getting the \phantom
and \quad
LaTeX commands to work in a legend label in matplotlib
.
Ideally I would like the 'PREV. < 15%' to be aligned with the label below such that the 'PREV.' line up. I can do this in a LaTeX document using the \phantom
or \quad
commands. However the following code produces the image seen above and I cannot figure out why these commands do not have any effect.
import matplotlib
matplotlib.rcParams['hatch.color'] = '#787878'
import matplotlib.pyplot as plt
from matplotlib.patches import Patch
CB = {'OrRd': ['#fef0d9', '#fdcc8a', '#fc8d59', '#e34a33', '#b30000']}
# Plot legend
legend_labels = [r'$\phantom{LONG TEST PHRASE} \textsc{Prev.} < %i\%%$' % (15),
r'$%i\%% \leq \textsc{Prev.} < %i\%%$' % (15, 25),
r'$%i\%% \leq \textsc{Prev.} < %i\%%$' % (25, 35),
r'$%i\%% \leq \textsc{Prev.} < %i\%%$' % (35, 45),
r'$%i\%% \leq \textsc{Prev.}$' % (45)]
legend_elements = [Patch(facecolor='#86838C', label='$\\textsc{N} < 20$',)] \
+ [Patch(facecolor='#ffffff', hatch='//', label='$20 \\leq \\textsc{N} \\leq 50$')] \
+ [Patch(facecolor=color, label=label) for color, label in zip(CB['OrRd'], legend_labels)]
plt.rc('text', usetex=True)
plt.rc('font', family='serif')
leg = plt.legend(handles=legend_elements, loc=2, fontsize=21,
frameon=False,
title=r'\textsc{LEGEND}', title_fontsize=24)
plt.show()