Putting newline in matplotlib label with TeX in Python?
Asked Answered
M

5

94

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.

Milissamilissent answered 17/4, 2010 at 22:32 Comment(0)
C
53

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

Cornstarch answered 17/4, 2010 at 22:37 Comment(4)
You might want to proactively double-escape LaTeX commands to make sure they are not interpreted by Python: xlabel('$\\Sigma$')Kosygin
This answer is not correct. You either double escape the latex `` in a normal string (no r) or you follow @EOLs answerLiliuokalani
regarding centering: ylabel('this is vertical\ntest', multialignment='center') from matplotlib.org/examples/pylab_examples/multiline.htmlSerotonin
Unfortunately none of the proposed solutions work with the option rcParams["text.usetex"] = TrueHassanhassell
C
137

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

Commuter answered 19/4, 2010 at 9:1 Comment(2)
Just a quick comment--this was the perfect solution for an easy way to label subplots with an (a), (b), etc. when that label should be below the plot and centered with the xlabel. This way plt.tight_layout() also sees the whole label and adjusts accordingly.Evanesce
This should be the accepted answer. Also note that it works with Python string formatting, e.g. r"$\alpha$ : {0} " "\n" r"$\beta$ : {1}".format(a, b)Phenoxide
C
53

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

Cornstarch answered 17/4, 2010 at 22:37 Comment(4)
You might want to proactively double-escape LaTeX commands to make sure they are not interpreted by Python: xlabel('$\\Sigma$')Kosygin
This answer is not correct. You either double escape the latex `` in a normal string (no r) or you follow @EOLs answerLiliuokalani
regarding centering: ylabel('this is vertical\ntest', multialignment='center') from matplotlib.org/examples/pylab_examples/multiline.htmlSerotonin
Unfortunately none of the proposed solutions work with the option rcParams["text.usetex"] = TrueHassanhassell
B
19
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.

Beautifully answered 7/11, 2014 at 3:1 Comment(0)
G
3

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}$')
Glutelin answered 28/4, 2014 at 16:19 Comment(0)
A
0

In case anyone wants TeX (e.g. for partly bold text) and a new line AND has a percentage sign in it (I struggled longer than I wanted):

import matplotlib.pyplot as plt

plt.plot([10, 20], [10, 20])  # dummy plot
value = 20  # dummy value

bold_text_base = f"Value = %u\ \%%"  # "\ " for protected space, "\%%" for percentage sign that survives formatting and math mode
regular_text = "(2nd line here)"
bold_text = bold_text_base % value
_ = plt.ylabel(r"$\bf{{{x}}}$".format(x=bold_text) + f"\n%s" % regular_text )  # suppress output with "_ = "

Returns:

Matplotlib plot with TeX, newline and percentage sign in title

Ascidium answered 28/4, 2023 at 13:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.