gpt4 book ai didi

python - 使用可变行号矩阵注释 matplotlib 图形

转载 作者:行者123 更新时间:2023-12-01 01:18:08 25 4
gpt4 key购买 nike

我正在尝试自动化 Python 中的一些绘图任务,其中之一需要使用方阵注释绘图。矩阵的行号可能会发生变化。我正在尝试使用 Latex 和 matplotlib 来执行此操作,但无法获取有效的 Latex 字符串:

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))

“打印(矩阵)”返回:

$ \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...'

我一直无法找出问题出在哪里,尽管它似乎与反斜杠有关。

最佳答案

您可以通过在每个字符串前添加一个 r 字符来解决此问题,这会将字符串转换为字节字符串,然后可由 LaTex 解析并正确渲染矩阵。这确实意味着字符串必须是逐字 LaTex 语法,请考虑以下示例

import numpy as np
import matplotlib.pyplot as plt

N=4

beginning=r"$ \left( \begin{array}{"
formatting=N*r'c'+r'}'
array_rows=(N-1)*((N-1)*r'%f & '+r'%f \\')
final_row=(N-1)*r'%f & '+r'%f '
end=r"\end{array} \right) $"

matrix=beginning+formatting+array_rows+final_row+end

a=np.random.randn(N,N)
vals=tuple(a.flatten())

fig,ax=plt.subplots(1)
ax.annotate(matrix % vals,(0.2,0.2))

Plot annotated with LaTex matrix

如果您尝试使用打印矩阵,这确实会使语法格式有点令人讨厌,因为\n字符必须从输入中删除,因为它们被解析为\\。但是编译后的 LaTex 注释将是正确的。

关于python - 使用可变行号矩阵注释 matplotlib 图形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54115631/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com