Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

python - matplotlib latex in legend label vs in axis label

For matplotlib, you can label legends and axis labels using tex command syntax. You're supposed to prepend r to the string: 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

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

MWE2 - Doesn't Crash

import numpy as np
import matplotlib.pyplot as plt
x = np.ones(5)
plt.plot(x, x, label="$ar{x}$ (but not really)") # I still don't need prepended r
plt.xlabel(r"$ar{y}$ (but not really)")
plt.show()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

That's no fair comparison. The plot label from MWE2 get's never used, because there is no legend; 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.

This crashes:

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

Result:

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

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"$ar{x}$ (but not really)") 
plt.xlabel(r"$ar{y}$ (but not really)")
plt.legend()
plt.show()

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...