Reputation: 189
I know there is a way to TeX inside the legend, but it doesn't understand arguments such as a line break or the matrix environment. I haven't been able to find any other resources that address drawing out a small matrix inside the legend itself, or even overlaying the matrix onto the plot. This is the best I can get:
with this code:
plt.plot(perturbation, errors,label=r'$A=[ 3 2 ][ 4 3 ]$')
plt.legend(loc='upper left', prop={'size': 12})
Thanks for any suggestions!
Upvotes: 0
Views: 599
Reputation: 36598
Matplotlib can use a LaTex engine, but you need to have it installed on your computer and set:
plt.rcParams['text.usetex'] = True
See here: https://matplotlib.org/stable/tutorials/text/usetex.html
The default is to use mathtext, a limited set of latex. Mathtext has not built-in matrix commands, but you can approximate it using \genfrac{}{}{}{}{}{}
. You do have to handle the whitespacing yourself. Example:
import numpy as np
from matplotlib import pyplot as plt
plt.ion()
x = np.linspace(0, 2 * np.pi, 300)
y = np.sin(x)
label = r'$A=\genfrac{[}{]}{0}{3}{\mathtt{\,3\;2}}{\mathtt{\,4\;3}}$'
plt.plot(x, y, label=label)
plt.legend(loc='lower left', prop={'size': 16})
Upvotes: 4
Reputation: 25023
For me it works
In [7]: import numpy as np
...: import matplotlib
...: matplotlib.rcParams['text.usetex'] = True
...: import matplotlib.pyplot as plt
...: t = np.linspace(0.0, 1.0, 100)
...: s = np.cos(4 * np.pi * t) + 2
...:
...: fig, ax = plt.subplots(figsize=(6, 4), tight_layout=True)
...: ax.plot(t, s)
...:
...: ax.set_xlabel(r'$\left[\matrix{ 1 & 0 \cr 0 & 1 }\right]$')
Out[7]: Text(0.5, 0, '$\\left[\\matrix{ 1 & 0 \\cr 0 & 1 }\\right]$')
Upvotes: 2