Search code examples
pythonplotgraphingmatplotlib

Putting newline in matplotlib label with TeX in Python?


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.


Solution

  • 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