gpt4 book ai didi

python - 图例标签与轴标签中的 matplotlib latex

转载 作者:太空宇宙 更新时间:2023-11-03 14:55:33 25 4
gpt4 key购买 nike

对于 matplotlib,您可以使用 tex 命令语法标记图例和轴标签。您应该将 r 添加到字符串:r"my tex label"。但我不明白的是,为什么图例标签关心轴标签却关心。

为什么轴标签的行为与图例标签不同(反之亦然)?

MWE1 - 崩溃

## Hello World! I crash!
import numpy as np
import matplotlib.pyplot as plt
x = np.ones(5)
plt.plot(x, x, label="$\bar{x}$ (but not really)")
plt.xlabel("$\bar{y}$ (but not really)") # I cause the crash
plt.show()

MWE2 - 不会崩溃

import numpy as np
import matplotlib.pyplot as plt
x = np.ones(5)
plt.plot(x, x, label="$\bar{x}$ (but not really)") # I still don't need prepended r
plt.xlabel(r"$\bar{y}$ (but not really)")
plt.show()

最佳答案

这不是公平的比较。 MWE2 get 中的情节标签从未使用过,因为没有图例;因此它不会引发任何错误。一旦您使用 plt.legend() 生成此图例,它当然会导致与您期望的所有其他包含 MathText 命令且不是原始字符串的字符串相同类型的错误。

这会崩溃:

import numpy as np
import matplotlib.pyplot as plt
x = np.ones(5)
plt.plot(x, x, label="$\bar{x}$ (but not really)")
plt.xlabel(r"$\bar{y}$ (but not really)")
plt.legend()
plt.show()

结果:

ValueError: 
$ar{x}$ (but not really)
^
Expected end of text, found '$' (at char 0), (line:1, col:1)

这不会崩溃,因为所有字符串都是原始字符串

import numpy as np
import matplotlib.pyplot as plt
x = np.ones(5)
plt.plot(x, x, label=r"$\bar{x}$ (but not really)")
plt.xlabel(r"$\bar{y}$ (but not really)")
plt.legend()
plt.show()

enter image description here

关于python - 图例标签与轴标签中的 matplotlib latex ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42914051/

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