2016-08-25 2 views
1

У меня проблема с номером Error saving matplotlib figures to pdf: 'str' object has no attribute 'decode', но без букв кириллицы. Мой код ниже:matplotlib не сохраняет pdf с латексом

# -*- coding: utf-8 -*- 
import matplotlib as mpl 
mpl.rcParams['backend'] = 'pdf' 
mpl.rc('font',**{'family':'serif'}) 
mpl.rc('text', usetex=True) 
mpl.rc('text.latex',unicode=True) 

import pandas as pd 
import seaborn as sns 
import matplotlib.pyplot as plt 
import numpy as np 
from matplotlib.ticker import FuncFormatter 

millionFormatter  = FuncFormatter(lambda x, pos:'\$%1.0fM' % (x*1e-6)) 
percentFormatter  = FuncFormatter(lambda x, pos:'{:.2%}'.format(x)) 

errorDF = pd.DataFrame({'% Diff':[ -6.12256893e-13, 1.27849915e-12, 6.29839396e-06, 
           3.38728472e-05, 6.23072435e-06, 5.03582306e-06, 
           -1.09295890e-05, 2.04080118e-04], 
        'Difference': [ -2.43408203e-01, 4.77478027e-01, 2.31911964e+06, 
            1.26799125e+07, 2.25939726e+06, 1.55594653e+06, 
            -3.10751878e+06, 5.58644987e+07]} 
        ,index = np.arange(2008,2016)) 

sns.set_style('ticks') 
fig = plt.figure(figsize=(5,2)) 
ax = fig.add_subplot(111) 
ax2 = ax.twinx() 
errorDF['% Diff'].plot(kind='bar', position=1, ax=ax, color = 'r', legend=True, label = 'Percent Error',ylim=(0,0.0005), **{'width':0.3}) 
errorDF.Difference.plot(kind='bar', position=0, ax=ax2,ylim=(0,80000000), legend=True, label = 'Absolute Error [secondary y-axis]', **{'width':0.3}) 
ax2.legend(loc= 'upper left') 
ax.set_xlabel('') 
ax2.set_xlabel('') 
ax.legend(bbox_to_anchor= (0.286,0.85)) 
ax.yaxis.set_major_formatter(percentFormatter) 
ax2.yaxis.set_major_formatter(millionFormatter) 
ax.yaxis.set_ticks([0,0.0001,0.0002,0.0003, 0.0004]) 
ax2.yaxis.set_ticks([0,20000000,40000000,60000000]) 
fig.savefig(r'C:\ . . .\dataerrors.pdf', bbox_inches='tight') 

Когда я пытаюсь сохранить фигуру в pdf, я получаю следующую трассировку.

Traceback (most recent call last): 
File "<ipython-input-46-ee8c792b07cc>", line 21, in <module> 
    fig.savefig(r'C:\Users\Chris\Documents\MIT\Dissertation\FPDS\Visualizations\USASpending\dataerrors.pdf', bbox_inches='tight',dpi=150) 
    File "C:\Users\Chris\Anaconda3\envs\py34\lib\site-packages\matplotlib\figure.py", line 1565, in savefig 
    self.canvas.print_figure(*args, **kwargs) 
    File "C:\Users\Chris\Anaconda3\envs\py34\lib\site-packages\matplotlib\backend_bases.py", line 2180, in print_figure 
**kwargs) 
    File "C:\Users\Chris\Anaconda3\envs\py34\lib\site-packages\matplotlib\backends\backend_pdf.py", line 2536, in print_pdf 
self.figure.draw(renderer) 
    File "C:\Users\Chris\Anaconda3\envs\py34\lib\site-packages\matplotlib\artist.py", line 61, in draw_wrapper 
    draw(artist, renderer, *args, **kwargs) 
    File "C:\Users\Chris\Anaconda3\envs\py34\lib\site-packages\matplotlib\figure.py", line 1159, in draw 
    func(*args) 
    File "C:\Users\Chris\Anaconda3\envs\py34\lib\site-packages\matplotlib\artist.py", line 61, in draw_wrapper 
    draw(artist, renderer, *args, **kwargs) 
    File "C:\Users\Chris\Anaconda3\envs\py34\lib\site-packages\matplotlib\axes\_base.py", line 2324, in draw 
    a.draw(renderer) 
    File "C:\Users\Chris\Anaconda3\envs\py34\lib\site-packages\matplotlib\artist.py", line 61, in draw_wrapper 
    draw(artist, renderer, *args, **kwargs) 
    File "C:\Users\Chris\Anaconda3\envs\py34\lib\site-packages\matplotlib\axis.py", line 1111, in draw 
    tick.draw(renderer) 
    File "C:\Users\Chris\Anaconda3\envs\py34\lib\site-packages\matplotlib\artist.py", line 61, in draw_wrapper 
    draw(artist, renderer, *args, **kwargs) 
    File "C:\Users\Chris\Anaconda3\envs\py34\lib\site-packages\matplotlib\axis.py", line 254, in draw 
    self.label2.draw(renderer) 
    File "C:\Users\Chris\Anaconda3\envs\py34\lib\site-packages\matplotlib\artist.py", line 61, in draw_wrapper 
    draw(artist, renderer, *args, **kwargs) 
    File "C:\Users\Chris\Anaconda3\envs\py34\lib\site-packages\matplotlib\text.py", line 792, in draw 
    mtext=mtext) 
    File "C:\Users\Chris\Anaconda3\envs\py34\lib\site-packages\matplotlib\backends\backend_pdf.py", line 1866, in draw_tex 
    psfont = self.tex_font_mapping(dvifont.texname) 
     File "C:\Users\Chris\Anaconda3\envs\py34\lib\site-packages\matplotlib\backends\backend_pdf.py", line 1568, in tex_font_mapping 
    return self.tex_font_map[texfont] 
    File "C:\Users\Chris\Anaconda3\envs\py34\lib\site-packages\matplotlib\dviread.py", line 701, in __getitem__ 
result = self._font[texname.decode('ascii')] 
AttributeError: 'str' object has no attribute 'decode' 

На рисунке покажет штраф в консоли, но выше ошибка возникает, когда я пытаюсь сохранить его в формате PDF.

Python 3.4 Matplotlib 1.5.1 Операционная система Windows 7

ответ

1

Кажется, что у меня была такая же проблема, вызванные отсутствием некоторых необходимых шрифтов в моей установке MikTex. Для меня было решение переустановить его со всеми пакетами, чтобы убедиться, что все шрифты сгенерированы. Я знаю, что это уродливое обходное решение, но оно полностью разрешило мою проблему. Я пробовал свой скрипт (только без морского берега, который не влияет на шрифты, я верю) и сгенерировал PDF.

Существует также другое обходное решение с XeTeX, вы можете взглянуть here.

+0

Это сработало! Вместо удаления/переустановки я смог использовать приложение MikTex Settings, а на вкладке «packages» добавить все шрифты. Определенно перебор, но он решил проблему. – lmum27

+0

Примечание. , , seaborn DOES влияет на стиль шрифта. На всякий случай, если другие пользователи на море будут пытаться подобным образом. – lmum27

+0

https://github.com/matplotlib/matplotlib/pull/6977 должно улучшить сообщение об ошибке, чтобы вы получили подсказку о том, какой шрифт отсутствует в файле PostScript. –