用Python中的TeX在matplotlib标签中添加换行符?

61 python graphing plot matplotlib

如何在matplotlib中为图表的标签添加换行符(例如xlabel或ylabel)?例如,

plt.bar([1, 2], [4, 5])
plt.xlabel("My x label")
plt.ylabel(r"My long label with $\Sigma_{C}$ math \n continues here") 
Run Code Online (Sandbox Code Playgroud)

理想情况下,我希望y-labeled也能居中.有没有办法做到这一点?标签同时包含TeX(包含在'$'中)和换行符非常重要.

Eri*_*got 88

您可以充分利用这两个方面:自动"转义"LaTeX命令换行符:

plt.ylabel(r"My long label with unescaped {\LaTeX} $\Sigma_{C}$ math"
           "\n"  # Newline: the backslash is interpreted as usual
           r"continues here with $\pi$")
Run Code Online (Sandbox Code Playgroud)

(而不是使用三行,用单个空格分隔字符串是另一种选择).

实际上,Python会自动连接彼此跟随的字符串文字,您可以将原始字符串(r"…")和字符串与字符插值("\n")混合.

  • 这应该是公认的答案。另请注意,它适用于 Python 字符串格式,例如 `r"$\alpha$ : {0} " "\n" r"$\beta$ : {1}".format(a, b)` (3认同)

Mic*_*zek 33

你使用的例子就是它的完成方式\n.您需要取消r前缀,因此python不会将其视为原始字符串

  • 您可能希望主动双重转义LaTeX命令,以确保它们不被Python解释:`xlabel('$ \\ Sigma $')` (7认同)
  • 这个答案是不正确的.你*要么*在正常的字符串中跳过乳胶`\`(没有r)*或*你跟着@EOLs [回答](http://stackoverflow.com/a/2666270/1157089) (7认同)
  • 关于居中:来自http://matplotlib.org/examples/pylab_examples/multiline.html的ylabel('this is vertical \ ntest',multialignment ='center')` (2认同)
  • 不幸的是,没有一个建议的解决方案与选项rcParams [“ text.usetex”] = True一起使用。 (2认同)

小智 11

plt.bar([1, 2], [4, 5])
plt.xlabel("My x label")
plt.ylabel(r"My long label with $\Sigma_{C}$ math" + "\n" + "continues here")
Run Code Online (Sandbox Code Playgroud)

只需将字符串与不是原始字符串形式的换行连接起来.