84

如何在 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") 

理想情况下,我希望 y 标记也可以居中。有没有办法做到这一点?重要的是标签同时包含 TeX(包含在“$”中)和换行符。

4

4 回答 4

121

您可以两全其美: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$")

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

事实上,Python 会自动连接彼此跟随的字符串文字,您可以混合使用原始字符串 ( r"…") 和带有字符插值 ( "\n") 的字符串。

于 2010-04-19T09:01:09.887 回答
49

您的示例正是它的完成方式,您使用\n. 你需要去掉 r 前缀所以python不会把它当作原始字符串

于 2010-04-17T22:37:40.773 回答
16
plt.bar([1, 2], [4, 5])
plt.xlabel("My x label")
plt.ylabel(r"My long label with $\Sigma_{C}$ math" + "\n" + "continues here")

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

于 2014-11-07T03:01:03.500 回答
3

以下 matplotlib python 脚本使用新行创建文本

ax.text(10, 70, 'shock size \n $n-n_{fd}$')

以下没有新行。注意文本前的 r

ax.text(10, 70, r'shock size \n $n-n_{fd}$')
于 2014-04-28T16:19:54.430 回答