在matplotlib中使用乳胶为字符串着色

时间:2020-08-28 16:31:50

标签: python matplotlib latex

我正在尝试在matplotlib中使用Latex并使用以下代码为字符串着色,请参见here

import matplotlib.pyplot as plt
import matplotlib
matplotlib.use('ps')
from matplotlib import rc

rc('text',usetex=True)
rc('text.latex', preamble='\usepackage{color}')

plt.figure()
plt.ylabel(r'\textcolor{red}{Today} '+
           r'\textcolor{green}{is} '+
           r'\textcolor{blue}{cloudy.}')

但是在执行上述代码时,出现以下错误:

 File "<ipython-input-38-6ffb8d156b19>", line 7
    rc('text.latex', preamble='\usepackage{color}')
                             ^
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 0-1: truncated \uXXXX escape

有人知道我应该在代码中添加/更新什么以消除错误,以便代码按预期正常运行吗?

1 个答案:

答案 0 :(得分:0)

您需要对\中的preamble='\usepackage{color}'字符进行转义。您有两个选择。

  1. 您可以使用原始字符串:

    rc('text.latex', preamble=r'\usepackage{color}')
    
  2. 您可以在字符串本身中转义\

    rc('text.latex', preamble='\\usepackage{color}')
    

    enter code here