'Multi-line title with variable in matplotlib
I'm using Matplotlib 3.1.2 and I'm trying to have a title that is split into two lines. I have a variable string in the plt.title() with latex formatting (r''). When I try the \newline or \n inside the string the output simply prints the \newline or \n as text and there's no line split. Here's my implementation:
plt.title(r'M$_{\rm{BH}}$ = 10$^{10}$ M$_{\odot}$, log U = %s, r$_{\rm{in}}$ = 10$^{18}$ cm'%(-1 + ((array1.tolist().index(i))*0.25)))
I tried adding a plt.suptitle() which does the job but there's an overlap between the two lines and I don't know how to add spacing/padding between them.
Solution 1:[1]
One possible solution is not to use raw-strings, but you need to escape the \:
plt.title('M$_{\\rm{BH}}$ = 10$^{10}$ M$_{\\odot}$\nlog U = %s\nr$_{\\rm{in}}$ = 10$^{18}$ cm'%('test'))
Solution 2:[2]
I was looking for a solution to this and got it working even with raw strings for LaTeX using:
import matplotlib.pyplot as plt
plt.title(r"Text $\omega$" + '\n' + r"$\delta$", multialignment='center')
or, with 3D plots:
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.set_title(r"Text $\omega$" + '\n' + r"$\delta$", multialignment='center')
It may or may not be necessary to use actual LaTeX rendering of text instead of Matplotlib's built-in MathTex. You can do this by:
import matplotlib.pyplot as plt
plt.rcParams.update({"text.usetex" : True})
Plus, I think it looks far nicer with it.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Diziet Asahi |
| Solution 2 | Kaserr |

