2

I am trying to colour a string using latex in matplotlib and using the following code, see 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.}')

But on executing the above code I am getting the following error:

 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

Does anyone know what should I add/update to the code to remove the error so that the code works perfectly as expected?

slothfulwave612
  • 1,349
  • 9
  • 22

1 Answers1

1

You need to escape the \ character in preamble='\usepackage{color}'. You have two options for this.

  1. you can use a raw string:

    rc('text.latex', preamble=r'\usepackage{color}')
    
  2. you can escape the \ in the string itself:

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

    enter code here

tmdavison
  • 64,360
  • 12
  • 187
  • 165