简体   繁体   English

图例标签中的matplotlib乳胶与轴标签中的比较

[英]matplotlib latex in legend label vs in axis label

For matplotlib, you can label legends and axis labels using tex command syntax. 对于matplotlib,您可以使用tex命令语法标记图例和轴标签。 You're supposed to prepend r to the string: r"my tex label". 应该在字符串前面添加r:r“my tex label”。 But what I don't understand is why the legend label doesn't care and yet the axis label does care. 但我不明白的是为什么传奇标签关心,但轴标签确实在乎。

Why do the axis labels behave differently than the legend label (or vice versa)? 为什么轴标签的行为与图例标签不同(反之亦然)?

MWE1 - Crashes 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 - Doesn't Crash 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()

That's no fair comparisson. 那是不公平的比较。 The plot label from MWE2 get's never used, because there is no legend; 来自MWE2的情节标签从未使用过,因为没有传说; therefore it will not raise any error. 因此它不会引起任何错误。 Once you produce this legend using plt.legend() it will of course cause the same kind of error that you'd expect from all other strings that contain MathText commands and are no raw strings. 一旦使用plt.legend()生成此图例,它当然会导致与包含MathText命令的所有其他字符串所期望的相同类型的错误,并且不是原始字符串。

This crashes: 这崩溃了:

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

This does not crash, as all strings are raw strings 这不会崩溃,因为所有字符串都是原始字符串

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM