matplotlib不保存PDF带乳胶 [英] matplotlib not saving pdf w/ latex

查看:63
本文介绍了matplotlib不保存PDF带乳胶的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到与

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')

当我尝试将图形保存为pdf时,会得到以下回溯.

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'

该数字将在控制台中很好地显示,但是当我尝试将其保存为pdf时会产生上述错误.

The figure will show fine in the console, but the above error is generated when i try to save it to pdf.

Python 3.4Matplotlib 1.5.1操作系统Windows 7

Python 3.4 Matplotlib 1.5.1 OS Windows 7

推荐答案

看来,由于MikTex安装中缺少某些必要的字体,我也遇到了同样的问题.对我来说,解决方案是将其与所有软件包一起重新安装,以确保生成了所有字体.我知道这是一个丑陋的解决方法,但是它完全解决了我的问题.我已经尝试过您的脚本(我相信,只有在没有seaborn的情况下,这才不会影响字体样式),并且生成了pdf.

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.

XeTeX还有另一个解决方法,您可以看看

There is also another workaround with XeTeX, you may have a look here.

这篇关于matplotlib不保存PDF带乳胶的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆