在matplotlib图例中为文本加下划线
我需要在图例下面加一段下划线的文字。我在这里找到一个相关的问题,但我完全不懂LaTeX。我想在图例中给“Content determined from gamma spectroscopy”加下划线(代码的第53行)。我尝试按照链接中的方法做:
r'\underline{Content determined from gamma spectroscopy} ',
但是那段文字在图例中只是原样显示出来了。我到底该怎么给文字加下划线呢?
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
eu_cl = 0.1
co_cl = 2.0
ca_eu_gs = 0.05 / eu_cl
ca_co_gs = 0.46 / co_cl
fa_eu_gs = 0.11 / eu_cl
fa_co_gs = 0.76 / co_cl
ce_eu_gs = 0.03 / eu_cl
ce_co_gs = 0.26 / co_cl
ca_eu_ms = 0.04 / eu_cl
ca_co_ms = 1.05 / co_cl
fa_eu_ms = 0.01 / eu_cl
fa_co_ms = 1.85 / co_cl
ce_eu_ms = 0.08 / eu_cl
ce_co_ms = 1.44 / co_cl
y_co = [1,1,1,1,1,1,1e-1,1e-2,1e-3,0]
x_co = [0,1e-4,1e-3,1e-2,1e-1,1e0,1e0,1e0,1e0,1e0]
#y_eu = [0, 1e-3, 1e-2, 1e-1, 1e0]
#x_eu = [1,1,1,1,1]
plt.rcParams['legend.loc'] = 'best'
plt.figure(1)
plt.ylim(1e-3, 1e4)
plt.xlim(1e-4, 1e3)
#plt.autoscale(enable=True, axis='y', tight=None)
#plt.autoscale(enable=True, axis='x', tight=None)
ca_gs = plt.scatter(ca_eu_gs, ca_co_gs, color='b', marker='o')
fa_gs = plt.scatter(fa_eu_gs, fa_co_gs, color='r', marker='o')
ce_gs = plt.scatter(ce_eu_gs, ce_co_gs, color='m', marker='o')
ca_ms = plt.scatter(ca_eu_ms, ca_co_ms, color='b', marker='^')
fa_ms = plt.scatter(fa_eu_ms, fa_co_ms, color='r', marker='^')
ce_ms = plt.scatter(ce_eu_ms, ce_co_ms, color='m', marker='^')
extra = Rectangle((0, 0), 1, 1, fc="w", fill=False, edgecolor='none', linewidth=0)
extra1 = Rectangle((0, 0), 1, 1, fc="w", fill=False, edgecolor='none', linewidth=0)
clearance, = plt.plot(x_co, y_co, color='g')
#plt.plot(x_eu, y_eu, color='g')
plt.loglog()
plt.xlabel('Europium (ppm)')
plt.ylabel('Cobalt (ppm)')
plt.legend([extra, ca_gs, fa_gs, ce_gs, extra1, ca_ms, fa_ms, ce_ms , clearance], ("Content determined from gamma spectroscopy" ,
"Coarse aggregate","Fine aggregate","Cement","Content determined from ICP-MS","Coarse aggregate","Fine aggregate","Cement","D/C = 1")
, scatterpoints = 1)
print('plots created')
plt.show()
编辑:
我按照评论中提到的,添加了以下内容来启用LaTeX:
rc('text', usetex=True)
但这导致了一堆错误,最后出现了以下错误:
RuntimeError: LaTeX was not able to process the following string:
'$10^{-4}$'
Here is the full report generated by LaTeX:
我猜这可能是因为我现在必须用LaTeX格式化我所有的文字。有没有办法只用LaTeX格式化其中一部分呢?我对LaTeX没有经验,现在也不是学习它的好时机(不过我总有一天会学的)。
2 个回答
1
你需要开启LaTeX渲染功能:
plt.rc('text', usetex=True)
关于LaTeX渲染的更多信息可以在这里找到:http://matplotlib.org/users/usetex.html
关于你提到的“LaTeX无法处理以下字符串”的编辑。
你不需要重新格式化所有文本。普通文本已经是LaTeX格式了,正如错误信息所示,matplotlib会自动把数字值转换成LaTeX格式(例如,1e-4
会变成$10^{-4}$
)。
我觉得问题可能是缺少一些软件包。如果你使用的是Ubuntu系统,确保安装了dvipng
、texlive-latex-extra
和texlive-math-extra
这些软件包。
2
之所以没成功,是因为你漏掉了
from matplotlib import rc
rc('text', usetex=True)
这个部分。LaTeX是一种标记语言,实际上是非常高级的语言。
如果你不想深入了解这个,可以直接用matplotlib的参数来设置图例的文字样式,不过这样会影响图例中的所有内容。