简体   繁体   English

在Matplotlib中对齐LaTeX刻度标签

[英]Aligning LaTeX ticklabels in Matplotlib

I have a simple Matplotlib plot with LaTeX ticklabels. 我有一个带有LaTeX ticklabels的简单Matplotlib图。 I'd like these to be centre-aligned so they all look even, but even with va='center' they appear to be at different vertical locations: 我希望它们居中对齐,以便它们看起来都一样,但是即使va='center'它们也似乎位于不同的垂直位置:

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

在此处输入图片说明

What can I do to align my xticklabels the way I want them? 我该怎么做才能使我的xticklabel对齐?

Try using the alignment keyword va='baseline' for the vertical alignment. 尝试使用对齐关键字va='baseline'进行垂直对齐。 This aligns the text on the baseline, meaning the bottom line of all letters without descender. 这将使文本在基线上对齐,这意味着所有字母的底行均不带下划线。 Theoretically all πs should line up nicely. 理论上,所有π都应该排列整齐。

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

This improved the plot for me, even though the labels still do not align perfectly. 即使标签仍然无法完美对齐,这也为我改善了情节。 More information can be found here . 可以在此处找到更多信息。 基线对齐图

Edit: 编辑:

This doesn't work for me, unfortunately. 不幸的是,这对我不起作用。 [...] I suspect this is a backend issue. [...]我怀疑这是一个后端问题。 - xnx -xnx

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. 这是svg,png和pdf后端生成的输出之间的比较,全部使用基线关键字。 Note that the pdf and svg labels line up almost perfectly so the pdf labels are not clearly visible. 请注意,pdf和svg标签几乎完美对齐,因此pdf标签不清晰可见。

后端比较

So for all purposes outside of the interactive viewer, using the pdf or svg backend looks good. 因此,出于交互式查看器之外的所有目的,使用pdf或svg后端看起来不错。 When using the png backend the labels are all over the place. 使用png后端时,标签到处都是。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM