Search code examples
matplotliblatexlegend

Latex \phantom command not rendering in matplotlib legend


I am having trouble getting the \phantom and \quad LaTeX commands to work in a legend label in matplotlib.

enter image description here

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()

Solution

  • The following solution is not perfect but I still think it's worth sharing with you. I adapted it from this more or less similar problem although the link problem is slightly different. As you can see, the alignment is not perfect. You might need to tweak it a little bit. I had to remove the title_fontsize from plt.legend() as it seems it is not compatible with matplotlib 2.2.2.

    matplotlib.rcParams['text.usetex'] = True
    matplotlib.rcParams['text.latex.preview'] = True
    
    # Plot legend
    legend_labels = [r'$\quad \quad \quad  \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)]
    

    enter image description here