用 Python 中的 TeX 在 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")

理想情况下,我希望 y 标签也能居中。有办法吗?标签必须同时包含 TeX (包含在’$’中)和换行符,这一点很重要。

122392 次浏览

Your example is exactly how it's done, you use \n. You need to take off the r prefix though so python doesn't treat it as a raw string

You can have the best of both worlds: automatic "escaping" of LaTeX commands and newlines:

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$")

(instead of using three lines, separating the strings by single spaces is another option).

In fact, Python automatically concatenates string literals that follow each other, and you can mix raw strings (r"…") and strings with character interpolation ("\n").

The following matplotlib python script creates text with new line

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

The following does not have new line. Notice the r before the text

ax.text(10, 70, r'shock size \n $n-n_{fd}$')
plt.bar([1, 2], [4, 5])
plt.xlabel("My x label")
plt.ylabel(r"My long label with $\Sigma_{C}$ math" + "\n" + "continues here")

Just concatenate the strings with a newline that isn't in raw string form.