我知道在图例中有一种 TeX 的方法,但它不理解诸如换行符或矩阵环境之类的参数。我无法找到任何其他资源来解决在图例本身内部绘制一个小矩阵,甚至将矩阵覆盖到图上的问题。
这是我能得到的最好的:
使用此代码:
plt.plot(perturbation, errors,label=r'$A=[ 3 2 ][ 4 3 ]$')
plt.legend(loc='upper left', prop={'size': 12})
感谢您的任何建议!
答案 0 :(得分:4)
Matplotlib 可以使用 LaTex 引擎,但您需要在您的计算机上安装并设置:
plt.rcParams['text.usetex'] = True
请看这里:https://matplotlib.org/stable/tutorials/text/usetex.html
默认使用 mathtext,一组有限的乳胶。 Mathtext 没有内置矩阵命令,但您可以使用 \genfrac{}{}{}{}{}{}
对其进行近似。你必须自己处理空格。示例:
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})
答案 1 :(得分:2)
对我来说它有效
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]$')