把换行符在matplotlib标签使用TeX的Python中?
-
27-09-2019 - |
题
如何添加一个新行到的曲线图的标签(例如xlabel或ylabel)在matplotlib?例如,
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(括在“$”)和换行符。
解决方案
您例子究竟它是如何做,你用\n
。你需要,但这样Python并不把它当作一个原始字符串起飞将R前缀
其他提示
可以有两全其美的:自动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"
)。
plt.bar([1, 2], [4, 5])
plt.xlabel("My x label")
plt.ylabel(r"My long label with $\Sigma_{C}$ math" + "\n" + "continues here")
只需串联串以换行,是不是在原始字符串的形式。
以下matplotlib Python脚本用新的线
创建文本ax.text(10, 70, 'shock size \n $n-n_{fd}$')
以下不具有新行。文本之前注意到第r
ax.text(10, 70, r'shock size \n $n-n_{fd}$')
不隶属于 StackOverflow