views:

205

answers:

2

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.

thanks.

+3  A: 

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

Michael Mrozek
You might want to proactively double-escape LaTeX commands to make sure they are not interpreted by Python: `xlabel('$\\Sigma$')`
honk
+1  A: 

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

plt.ylabel(r"My long label with $\Sigma_{C}$ math"      "\n"       r"continues here with $\pi$")

(spaces added for legibility). In fact, Python automatically concatenates strings that follow each other.

EOL