Aligning LaTeX ticklabels in Matplotlib
<p>I have a simple Matplotlib plot with LaTeX ticklabels. I'd like these to be centre-aligned so they all look even, but even with <code>va='center'</code> they appear to be at different vertical locations:</p>

<pre><code>import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl

# Some Matplotlib settings so the font is consistent
mpl.rc('font', **{'family': 'serif', 'serif': ['Computer Modern'],
                  'size': 20})
mpl.rc('text', usetex=True)

theta = np.linspace(-np.pi, np.pi, 100)

fig, ax = plt.subplots()
ax.plot(theta, np.cos(theta))

ax.set_xticks(np.linspace(-np.pi, np.pi, 5))
ax.set_xticklabels((r'$-\pi$', r'$-\pi/2$', '0',
                    r'$\pi/2$', r'$\pi$'), va='center')
ax.tick_params(axis='x', which='major', pad=20)
plt.show()
</code></pre>

<p><a href="http://i.stack.imgur.com/6UoRw.png" rel="nofollow"><img src="http://i.stack.imgur.com/6UoRw.png" alt="enter image description here"></a></p>

<p>What can I do to align my xticklabels the way I want them?</p>

<p>Try using the alignment keyword <code>va='baseline'</code> for the vertical alignment. This aligns the text on the baseline, meaning the bottom line of all letters without descender. Theoretically all Ïs should line up nicely. </p>

<pre><code>ax.set_xticklabels((r'$-\pi$', r'$-\pi/2$', '0',
                    r'$\pi/2$', r'$\pi$'), va='baseline')
</code></pre>

<p>This improved the plot for me, even though the labels still do not align perfectly. More information can be found <a href="https://github.com/matplotlib/matplotlib/issues/1734/" rel="nofollow">here</a>.
<a href="http://i.stack.imgur.com/m6qof.png" rel="nofollow"><img src="http://i.stack.imgur.com/m6qof.png" alt="baseline aligned plot"></a></p>

<h2>Edit:</h2>

<blockquote>
  <p>This doesn't work for me, unfortunately. [...] I suspect this is a backend issue. - xnx</p>
</blockquote>

<p>The position of the labels change with the used backend. Here is a comparison between the output generated by svg, png and pdf backend, all using the baseline keyword. Note that the pdf and svg labels line up almost perfectly so the pdf labels are not clearly visible. </p>

<p><a href="http://i.stack.imgur.com/huVJo.png" rel="nofollow"><img src="http://i.stack.imgur.com/huVJo.png" alt="Comparison of backends"></a></p>

<p>So for all purposes outside of the interactive viewer, using the pdf or svg backend looks good. When using the png backend the labels are all over the place.</p>

python matplotlib