问题
I am having an issue simular to Error saving matplotlib figures to pdf: 'str' object has no attribute 'decode', but without the cyrillic letters. My code is below:
# -*- 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')
When i try to save the figure to a pdf, i get the following traceback.
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'
The figure will show fine in the console, but the above error is generated when i try to save it to pdf.
Python 3.4 Matplotlib 1.5.1 OS Windows 7
回答1:
It seems that I had the same issue caused by the lack of some necessary fonts in my MikTex installation. For me the solution was to reinstall it with all packages to make sure that all fonts are generated. I know that is an ugly workaround, but it solved my problem completely. I've tried your script (only without seaborn, which does not affect fontstyles, I beleive) and generated pdf.
There is also another workaround with XeTeX, you may have a look here.
回答2:
in my case I am using MiKTeX, when I try to save the latex typesetting figure as PDF, I got the following error :
runfile('C:/Users/yl7316/.spyder-py3/Pricing2/PostageStamp/Plot.py', wdir='C:/Users/yl7316/.spyder-py3/Pricing2/PostageStamp')
Traceback (most recent call last):
File "<ipython-input-99-08a0bdbc1356>", line 1, in <module>
runfile('C:/Users/yl7316/.spyder-py3/Pricing2/PostageStamp/Plot.py', wdir='C:/Users/yl7316/.spyder-py3/Pricing2/PostageStamp')
File "C:\Users\yl7316\AppData\Local\Continuum\anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 827, in runfile
execfile(filename, namespace)
File "C:\Users\yl7316\AppData\Local\Continuum\anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 110, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "C:/Users/yl7316/.spyder-py3/Pricing2/PostageStamp/Plot.py", line 41, in <module>
fig1.savefig('TIC_Plot.pdf')
File "C:\Users\yl7316\AppData\Local\Continuum\anaconda3\lib\site-packages\matplotlib\figure.py", line 2180, in savefig
self.canvas.print_figure(fname, **kwargs)
File "C:\Users\yl7316\AppData\Local\Continuum\anaconda3\lib\site-packages\matplotlib\backend_bases.py", line 2082, in print_figure
**kwargs)
File "C:\Users\yl7316\AppData\Local\Continuum\anaconda3\lib\site-packages\matplotlib\backends\backend_pdf.py", line 2503, in print_pdf
self.figure.draw(renderer)
File "C:\Users\yl7316\AppData\Local\Continuum\anaconda3\lib\site-packages\matplotlib\artist.py", line 38, in draw_wrapper
return draw(artist, renderer, *args, **kwargs)
File "C:\Users\yl7316\AppData\Local\Continuum\anaconda3\lib\site-packages\matplotlib\figure.py", line 1709, in draw
renderer, self, artists, self.suppressComposite)
File "C:\Users\yl7316\AppData\Local\Continuum\anaconda3\lib\site-packages\matplotlib\image.py", line 135, in _draw_list_compositing_images
a.draw(renderer)
File "C:\Users\yl7316\AppData\Local\Continuum\anaconda3\lib\site-packages\matplotlib\artist.py", line 38, in draw_wrapper
return draw(artist, renderer, *args, **kwargs)
File "C:\Users\yl7316\AppData\Local\Continuum\anaconda3\lib\site-packages\matplotlib\axes\_base.py", line 2647, in draw
mimage._draw_list_compositing_images(renderer, self, artists)
File "C:\Users\yl7316\AppData\Local\Continuum\anaconda3\lib\site-packages\matplotlib\image.py", line 135, in _draw_list_compositing_images
a.draw(renderer)
File "C:\Users\yl7316\AppData\Local\Continuum\anaconda3\lib\site-packages\matplotlib\artist.py", line 38, in draw_wrapper
return draw(artist, renderer, *args, **kwargs)
File "C:\Users\yl7316\AppData\Local\Continuum\anaconda3\lib\site-packages\matplotlib\axis.py", line 1217, in draw
self.label.draw(renderer)
File "C:\Users\yl7316\AppData\Local\Continuum\anaconda3\lib\site-packages\matplotlib\artist.py", line 38, in draw_wrapper
return draw(artist, renderer, *args, **kwargs)
File "C:\Users\yl7316\AppData\Local\Continuum\anaconda3\lib\site-packages\matplotlib\text.py", line 714, in draw
mtext=mtext)
File "C:\Users\yl7316\AppData\Local\Continuum\anaconda3\lib\site-packages\matplotlib\backends\backend_pdf.py", line 1909, in draw_tex
pdfname = self.file.dviFontName(dvifont)
File "C:\Users\yl7316\AppData\Local\Continuum\anaconda3\lib\site-packages\matplotlib\backends\backend_pdf.py", line 674, in dviFontName
psfont = tex_font_map[dvifont.texname]
File "C:\Users\yl7316\AppData\Local\Continuum\anaconda3\lib\site-packages\matplotlib\dviread.py", line 821, in __getitem__
result = self._font[texname]
KeyError: b'tcrm1728'
Then I search texfont 'tcrm1728' online and found the PDF document The fix-cm package indicating 'tcrm1728' font is under 'TS1 encoding CM Roman', then I went to MiKTeX webpage and install most likely relevant packages, in my case are "cm-super" and "cm-unicode", and update package "ec" and "cm".
In addition, I have made sure the windows system-wise PATH variable already contains the installation directory of latest MiKTeX and Ghostscript.
Hope this work flow does help.
来源:https://stackoverflow.com/questions/39151477/matplotlib-not-saving-pdf-w-latex