Я пытаюсь автоматизировать некоторые задачи по построению, которые у меня есть в Python, одна из которых требует аннотирования графика с помощью квадратной матрицы. Номер строки матрицы может быть изменен.
Я пытаюсь использовать для этого латекс и matplotlib, но не могу получить правильную строку латекса:
import numpy as np
import matplotlib.pyplot as plt
#Number of rows of matrix
N=4
#create what I believe to be the valid Latex instruction:
beginning="$ \\left( \\begin{array}{"
formatting=N*'c'+'}\n'
array_rows=(N-1)*((N-1)*'%f & '+'%f \\\\\n')
final_row=(N-1)*'%f & '+'%f '
end="\\end{array} \\right) $"
matrix=beginning+formatting+array_rows+final_row+end
#generate some random values for the matrix and put them in a flat tuple
a=np.random.randn(N,N)
vals=tuple(a.flatten())
#attempt to annotate a plot:
fig,ax=plt.subplots(1)
ax.annotate(matrix % vals,(0.2,0.2))
print (matrix) 'возвращает:
$ \left( \begin{array}{cccc}
%f & %f & %f & %f \\
%f & %f & %f & %f \\
%f & %f & %f & %f \\
%f & %f & %f & %f \end{array} \right) $
, что я и ожидаю, но 'ax.annotate (matrix% vals, (0.2,0.2))' возвращает:
'RuntimeError: latex was not able to process the following string:
b'$ \\\\left( \\\\begin{array}{cccc}0.587986 & -0.670847 & 1.424638 & 1.416569 \\\\1.961583 & 2.134095 & 0.296239 & -0.737057 \\\\0.311355 & 0.018828 & 0.031258 & -1.443867 \\\\0.964141 & 0.686492 & -1.367708 & -1.353436\\\\end{array} \\right) $''
'! Undefined control sequence.
l.13 ...87986 & -0.670847 & 1.424638 & 1.416569 \1.961583 & 2.134095
& 0.296...'
Мне не удалось выяснить, где проблема, хотя, похоже, это связано с обратными слешами.