Putting newline in matplotlib label with TeX in Python?

PythonPlotGraphingMatplotlib

Python Problem Overview


How can I add a newline to a plot's label (e.g. xlabel or ylabel) in matplotlib? For example,

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

Ideally I'd like the y-labeled to be centered too. Is there a way to do this? It's important that the label have both TeX (enclosed in '$') and the newline.

Python Solutions


Solution 1 - Python

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

Solution 2 - Python

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

Solution 3 - Python

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.

Solution 4 - Python

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}$')

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser248237View Question on Stackoverflow
Solution 1 - PythonEric O LebigotView Answer on Stackoverflow
Solution 2 - PythonMichael MrozekView Answer on Stackoverflow
Solution 3 - PythonBrothamanView Answer on Stackoverflow
Solution 4 - PythonRanaivoView Answer on Stackoverflow