UnicodeError problem when trying to save a figure with latex text in Matplotlib

0

Speak up. I am having a problem using the MatPlotLib library. Before the last update of Windows I used the library without any problem. I use it basically to create function graphs and save them in .pdf using Latex formatting for text, below is a sample code:

import numpy as np
from matplotlib import pyplot as plt

# Data for plot
step = 0.001
x = np.arange(0, 2 + step, step)
y = x*x*np.cos(10*x)

plt.rc('text', usetex=True)
 plt.rc('font', family='serif')
plt.figure(figsize=(19.2, 10.8))

plt.plot(x, y, lw=2)
plt.title(r'Function $f(x) = x^2 \cos(10x)$')
plt.savefig('plot.pdf', bbox_inches='tight')
plt.show()
plt.close()

But after the update my old windows bugged and I had to format the pc, and now I can no longer use the same code above and save the figures in .pdf, the following error happens:

File "C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\dviread.py", line 1057, in find_tex_file
 return result.decode('ascii')

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 10: ordinal not in range(128)

Using the same code I am able to save in other formats, for example .png and .eps. After formatting I basically installed the same software I used before.

Ps. The code above was tested in Spyder 3.2.6 and PyCharm 2018.1.3 with version 3.6.4 of Python. The Latex is working perfectly. I use MikTex for the Latex base and the TexStudio editor.

    
asked by anonymous 27.05.2018 / 19:59

2 answers

0

So after a lot of suffering I solved the problem.

To use latex, the matplotlib library uses the registration path to access the Miktex workplace. It turns out that the username I was using was Fabio, with the accent. So when the library tried to access the path it would find a path, which when used to export the figure, resulted in UnicodeDecodeError.

So I created another Fabio user, deleted the old one and reinstalled Miktex. After that the error stopped.

    
30.05.2018 / 05:16
1

plot.pdf probably contains accents, maybe set at the top of the document:

# -*- coding: utf-8 -*-

import numpy as np
from matplotlib import pyplot as plt
...

If running via cmd run before running your script:

chcp 65001

As the example in link

For utf-8 you may also have to add:

from __future__ import unicode_literals

It should look like this:

# -*- coding: utf-8 -*-

from __future__ import unicode_literals

import numpy as np

from matplotlib import pyplot as plt
...
    
27.05.2018 / 20:56