gpt4 book ai didi

matplotlib - Matplotlib-在LateX表达式中使用变量

转载 作者:行者123 更新时间:2023-12-03 13:58:22 33 4
gpt4 key购买 nike

我想使用LateX格式来构建一个表达式,其中出现一些数字,但这些数字是用LateX表达式中的变量表示的。

实际的目标是在axes.annotate()方法中使用它,但是为了讨论起见,这里是一个原理代码:

import matplotlib.pyplot as plt
import numpy as np
x = np.arange(-5, 5, 0.05)
fig = plt.plot(x, x**2)
plt.grid(True)
g = 3
plt.xlabel(r'$test {}$'.format(g))
plt.show()

可以,将 g的值传递给表达式。

但是,如何使用 \frac{}{}和其他结构呢?
将上面的 xlabel()字符串替换为:
plt.xlabel(r'$test \frac{1}{}$'.format(g))

给出:
IndexError: tuple index out of range

我知道使用花括号正在发生某些事情,并且尝试了几种变体,但到目前为止没有任何效果。

最佳答案

花括号可以通过加倍转义,但format替换g后会删除一对(并且frac期望花括号中的参数),因此分母需要三对

plt.xlabel(r'$test \frac{{1}}{{{}}}$'.format(g))

关于matplotlib - Matplotlib-在LateX表达式中使用变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33786332/

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