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")混合.
Mic*_*zek 33
你使用的例子就是它的完成方式\n.您需要取消r前缀,因此python不会将其视为原始字符串
小智 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)
只需将字符串与不是原始字符串形式的换行连接起来.