Skip to content

figure including align fails to output eps using savefig #11233

Open

Description

@nedlrichards

trouble with latex align and eps output

png output works, eps breaks

I have a figure that contains an align latex environment to stack two parameter definitions. Saving the figure as png is OK, while as eps gives a complicated Latex error.

import matplotlib
import matplotlib.pyplot as plt

params= {'text.latex.preamble' : [r'\usepackage{amsmath}']}
plt.rcParams.update(params)

fig, ax = plt.subplots(figsize=(8, 6))
ax.text(0.5, 0.5, r'\begin{align*} H&: 2 \ \textrm{m} \\'\
                 + r'\Lambda &: 40 \ \textrm{m} \end{align*}',
         bbox=dict(boxstyle="square",
                   ec=(0.6, 0.6, 0.6),
                   fc=(1., 1., 1.),
                   ),
        fontsize=32)

plt.show(block=False)
# this works fine
#plt.savefig('test.png', format='png')
plt.savefig('test.eps', format='eps')

Actual outcome

---------------------------------------------------------------------------
CalledProcessError                        Traceback (most recent call last)
~/miniconda3/lib/python3.6/site-packages/matplotlib/backends/backend_ps.py in convert_psfrags(tmpfile, psfrags, font_preamble, custom_preamble, paperWidth, paperHeight, orientation)
   1435         report = subprocess.check_output(command, cwd=tmpdir,
-> 1436                                          stderr=subprocess.STDOUT)
   1437     except subprocess.CalledProcessError as exc:

~/miniconda3/lib/python3.6/subprocess.py in check_output(timeout, *popenargs, **kwargs)
    335     return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
--> 336                **kwargs).stdout
    337 

~/miniconda3/lib/python3.6/subprocess.py in run(input, timeout, check, *popenargs, **kwargs)
    417             raise CalledProcessError(retcode, process.args,
--> 418                                      output=stdout, stderr=stderr)
    419     return CompletedProcess(process.args, retcode, stdout, stderr)

CalledProcessError: Command '['latex', '-interaction=nonstopmode', '"/tmp/tmpdnuve0l3.tex"']' returned non-zero exit status 1.

During handling of the above exception, another exception occurred:

RuntimeError                              Traceback (most recent call last)
~/python-workspace/icepyks/workspace/essay_plots/eps_bug.py in <module>()
     21 plt.show(block=False)
     22 #plt.savefig('test.png', format='png')
---> 23 plt.savefig('test.eps', format='eps')

~/miniconda3/lib/python3.6/site-packages/matplotlib/pyplot.py in savefig(*args, **kwargs)
    708 def savefig(*args, **kwargs):
    709     fig = gcf()
--> 710     res = fig.savefig(*args, **kwargs)
    711     fig.canvas.draw_idle()   # need this if 'transparent=True' to reset colors
    712     return res

~/miniconda3/lib/python3.6/site-packages/matplotlib/figure.py in savefig(self, fname, **kwargs)
   2033             self.set_frameon(frameon)
   2034 
-> 2035         self.canvas.print_figure(fname, **kwargs)
   2036 
   2037         if frameon:

~/miniconda3/lib/python3.6/site-packages/matplotlib/backend_bases.py in print_figure(self, filename, dpi, facecolor, edgecolor, orientation, format, **kwargs)
   2259                 orientation=orientation,
   2260                 bbox_inches_restore=_bbox_inches_restore,
-> 2261                 **kwargs)
   2262         finally:
   2263             if bbox_inches and restore_bbox:

~/miniconda3/lib/python3.6/site-packages/matplotlib/backends/backend_ps.py in print_eps(self, outfile, *args, **kwargs)
    929 
    930     def print_eps(self, outfile, *args, **kwargs):
--> 931         return self._print_ps(outfile, 'eps', *args, **kwargs)
    932 
    933     def _print_ps(self, outfile, format, *args, **kwargs):

~/miniconda3/lib/python3.6/site-packages/matplotlib/backends/backend_ps.py in _print_ps(self, outfile, format, *args, **kwargs)
    953             self._print_figure_tex(outfile, format, imagedpi, facecolor, edgecolor,
    954                                    orientation, isLandscape, papertype,
--> 955                                    **kwargs)
    956         else:
    957             self._print_figure(outfile, format, imagedpi, facecolor, edgecolor,

~/miniconda3/lib/python3.6/site-packages/matplotlib/backends/backend_ps.py in _print_figure_tex(self, outfile, format, dpi, facecolor, edgecolor, orientation, isLandscape, papertype, metadata, **kwargs)
   1349                                              custom_preamble, paperWidth,
   1350                                              paperHeight,
-> 1351                                              orientation)
   1352 
   1353             if (rcParams['ps.usedistiller'] == 'ghostscript'

~/miniconda3/lib/python3.6/site-packages/matplotlib/backends/backend_ps.py in convert_psfrags(tmpfile, psfrags, font_preamble, custom_preamble, paperWidth, paperHeight, orientation)
   1441              'Here is the full report generated by LaTeX:\n%s '
   1442              '\n\n' % (latexfile,
-> 1443                        exc.output.decode("utf-8"))))
   1444     _log.debug(report)
   1445 

RuntimeError: LaTeX was not able to process the following file:
/tmp/tmpdnuve0l3.tex

Here is the full report generated by LaTeX:
This is pdfTeX, Version 3.14159265-2.6-1.40.18 (TeX Live 2017) (preloaded format=latex)
 restricted \write18 enabled.
entering extended mode
(/tmp/tmpdnuve0l3.tex
LaTeX2e <2017-04-15>
Babel <3.15> and hyphenation patterns for 84 language(s) loaded.
(/home/e2richards/texlive/2017/texmf-dist/tex/latex/base/article.cls
Document Class: article 2014/09/29 v1.4h Standard LaTeX document class
(/home/e2richards/texlive/2017/texmf-dist/tex/latex/base/size10.clo))
(/home/e2richards/texlive/2017/texmf-dist/tex/latex/type1cm/type1cm.sty)
(/home/e2richards/texlive/2017/texmf-dist/tex/latex/base/textcomp.sty
(/home/e2richards/texlive/2017/texmf-dist/tex/latex/base/ts1enc.def))
(/home/e2richards/texlive/2017/texmf-dist/tex/latex/amsmath/amsmath.sty
For additional information on amsmath, use the `?' option.
(/home/e2richards/texlive/2017/texmf-dist/tex/latex/amsmath/amstext.sty
(/home/e2richards/texlive/2017/texmf-dist/tex/latex/amsmath/amsgen.sty))
(/home/e2richards/texlive/2017/texmf-dist/tex/latex/amsmath/amsbsy.sty)
(/home/e2richards/texlive/2017/texmf-dist/tex/latex/amsmath/amsopn.sty))
(/home/e2richards/texlive/2017/texmf-dist/tex/latex/geometry/geometry.sty
(/home/e2richards/texlive/2017/texmf-dist/tex/latex/graphics/keyval.sty)
(/home/e2richards/texlive/2017/texmf-dist/tex/generic/oberdiek/ifpdf.sty)
(/home/e2richards/texlive/2017/texmf-dist/tex/generic/oberdiek/ifvtex.sty)
(/home/e2richards/texlive/2017/texmf-dist/tex/generic/ifxetex/ifxetex.sty)

Package geometry Warning: Over-specification in `h'-direction.
    `width' (578.15999pt) is ignored.


Package geometry Warning: Over-specification in `v'-direction.
    `height' (433.62pt) is ignored.

) (/home/e2richards/texlive/2017/texmf-dist/tex/latex/psfrag/psfrag.sty
(/home/e2richards/texlive/2017/texmf-dist/tex/latex/graphics/graphics.sty
(/home/e2richards/texlive/2017/texmf-dist/tex/latex/graphics/trig.sty)
(/home/e2richards/texlive/2017/texmf-dist/tex/latex/graphics-cfg/graphics.cfg)
(/home/e2richards/texlive/2017/texmf-dist/tex/latex/graphics-def/dvips.def)))
(/home/e2richards/texlive/2017/texmf-dist/tex/latex/graphics/graphicx.sty)
(/home/e2richards/texlive/2017/texmf-dist/tex/latex/graphics/color.sty
(/home/e2richards/texlive/2017/texmf-dist/tex/latex/graphics-cfg/color.cfg)
(/home/e2richards/texlive/2017/texmf-dist/tex/latex/graphics/dvipsnam.def))
No file tmpdnuve0l3.aux.
(/home/e2richards/texlive/2017/texmf-dist/tex/latex/base/ts1cmr.fd)
*geometry* detected driver: dvips
<tmpdnuve0l3.eps>

LaTeX Font Warning: Font shape `OMX/cmex/m/n' in size <26> not available
(Font)              size <24.88> substituted on input line 28.


LaTeX Font Warning: Font shape `OMX/cmex/m/n' in size <18.19992> not available
(Font)              size <17.28> substituted on input line 28.


LaTeX Font Warning: Font shape `OMX/cmex/m/n' in size <13> not available
(Font)              size <12> substituted on input line 28.


LaTeX Font Warning: Font shape `OMX/cmex/m/n' in size <32> not available
(Font)              size <24.88> substituted on input line 28.


LaTeX Font Warning: Font shape `OMX/cmex/m/n' in size <22.3999> not available
(Font)              size <20.74> substituted on input line 28.


LaTeX Font Warning: Font shape `OMX/cmex/m/n' in size <16> not available
(Font)              size <17.28> substituted on input line 28.

! Missing \endgroup inserted.
<inserted text> 
                \endgroup 
l.28 \includegraphics*[angle=0]{tmpdnuve0l3.eps}
                                                
! Missing } inserted.
<inserted text> 
                }
l.28 \includegraphics*[angle=0]{tmpdnuve0l3.eps}
                                                
! Missing \endgroup inserted.
<inserted text> 
                \endgroup 
l.28 \includegraphics*[angle=0]{tmpdnuve0l3.eps}
                                                
! Missing } inserted.
<inserted text> 
                }
l.28 \includegraphics*[angle=0]{tmpdnuve0l3.eps}
                                                

! LaTeX Error: There's no line here to end.

See the LaTeX manual or LaTeX Companion for explanation.
Type  H <return>  for immediate help.
 ...                                              
                                                  
l.28 \includegraphics*[angle=0]{tmpdnuve0l3.eps}
                                                
! Missing $ inserted.
<inserted text> 
                $
l.28 \includegraphics*[angle=0]{tmpdnuve0l3.eps}
                                                
! Missing } inserted.
<inserted text> 
                }
l.28 \includegraphics*[angle=0]{tmpdnuve0l3.eps}
                                                
! Missing } inserted.
<inserted text> 
                }
l.28 \includegraphics*[angle=0]{tmpdnuve0l3.eps}
                                                
! Missing } inserted.
<inserted text> 
                }
l.28 \includegraphics*[angle=0]{tmpdnuve0l3.eps}
                                                
! Missing \cr inserted.
<inserted text> 
                \cr 
l.28 \includegraphics*[angle=0]{tmpdnuve0l3.eps}
                                                
! Missing { inserted.
<inserted text> 
                {
l.28 \includegraphics*[angle=0]{tmpdnuve0l3.eps}
                                                
! Missing { inserted.
<inserted text> 
                {
l.28 \includegraphics*[angle=0]{tmpdnuve0l3.eps}
                                                
! Extra }, or forgotten $.
<recently read> }
                 
l.28 \includegraphics*[angle=0]{tmpdnuve0l3.eps}
                                                
! Missing $ inserted.
<inserted text> 
                $
l.28 \includegraphics*[angle=0]{tmpdnuve0l3.eps}
                                                
! Missing } inserted.
<inserted text> 
                }
l.28 \includegraphics*[angle=0]{tmpdnuve0l3.eps}
                                                
! Missing $ inserted.
<inserted text> 
                $
l.28 \includegraphics*[angle=0]{tmpdnuve0l3.eps}
                                                
! Misplaced alignment tab character &.
<argument>  H&: 2 \ \textrm {m} \\\Lambda &
                                           : 40 \ \textrm {m} 
l.28 \includegraphics*[angle=0]{tmpdnuve0l3.eps}
                                                
! Misplaced \cr.
\math@cr@@@ ->\cr 
                  
l.28 \includegraphics*[angle=0]{tmpdnuve0l3.eps}
                                                
! Misplaced \noalign.
\math@cr@@ ... \iffalse }\fi \math@cr@@@ \noalign 
                                                  {\vskip #1\relax }
l.28 \includegraphics*[angle=0]{tmpdnuve0l3.eps}
                                                
! Missing $ inserted.
<inserted text> 
                $
l.28 \includegraphics*[angle=0]{tmpdnuve0l3.eps}
                                                
! Missing } inserted.
<inserted text> 
                }
l.28 \includegraphics*[angle=0]{tmpdnuve0l3.eps}
                                                
! Extra }, or forgotten \endgroup.
\math@cr@@ ...th@cr@@@ \noalign {\vskip #1\relax }
                                                  
l.28 \includegraphics*[angle=0]{tmpdnuve0l3.eps}
                                                
! Misplaced \noalign.
\black@ #1->\noalign 
                     {\ifdim #1>\displaywidth \dimen@ \prevdepth \nointerlin...
l.28 \includegraphics*[angle=0]{tmpdnuve0l3.eps}
                                                

Overfull \hbox (118.28842pt too wide) detected at line 28
[]
! Extra }, or forgotten \endgroup.
\endalign ->\math@cr \black@ \totwidth@ \egroup 
                                                \ifingather@ \restorealignst...
l.28 \includegraphics*[angle=0]{tmpdnuve0l3.eps}
                                                

! LaTeX Error: \begin{figure} on input line 15 ended by \end{align*}.

See the LaTeX manual or LaTeX Companion for explanation.
Type  H <return>  for immediate help.
 ...                                              
                                                  
l.28 \includegraphics*[angle=0]{tmpdnuve0l3.eps}
                                                
! Missing $ inserted.
<inserted text> 
                $
l.28 \includegraphics*[angle=0]{tmpdnuve0l3.eps}
                                                
! Display math should end with $$.
<to be read again> 
                   \endgroup 
l.28 \includegraphics*[angle=0]{tmpdnuve0l3.eps}
                                                
! Missing } inserted.
<inserted text> 
                }
l.28 \includegraphics*[angle=0]{tmpdnuve0l3.eps}
                                                
! Missing } inserted.
<inserted text> 
                }
l.28 \includegraphics*[angle=0]{tmpdnuve0l3.eps}
                                                
! Extra }, or forgotten \endgroup.
\Gin@erotate ...angle {#1}\setbox \z@ \hbox {{#2}}
                                                  \Grot@x \z@ \Grot@y \z@ \G...
l.28 \includegraphics*[angle=0]{tmpdnuve0l3.eps}
                                                
! Undefined control sequence.
<argument> \Grot@angle 
                       
l.28 \includegraphics*[angle=0]{tmpdnuve0l3.eps}
                                                
! Missing number, treated as zero.
<to be read again> 
                   )
l.28 \includegraphics*[angle=0]{tmpdnuve0l3.eps}
                                                
! Undefined control sequence.
<argument> \Grot@angle 
                       
l.28 \includegraphics*[angle=0]{tmpdnuve0l3.eps}
                                                
! Missing number, treated as zero.
<to be read again> 
                   )
l.28 \includegraphics*[angle=0]{tmpdnuve0l3.eps}
                                                
! Undefined control sequence.
<argument> \Grot@angle 
                       
l.28 \includegraphics*[angle=0]{tmpdnuve0l3.eps}
                                                
! Missing number, treated as zero.
<to be read again> 
                   )
l.28 \includegraphics*[angle=0]{tmpdnuve0l3.eps}
                                                
! Undefined control sequence.
<argument> \Grot@angle 
                       
l.28 \includegraphics*[angle=0]{tmpdnuve0l3.eps}
                                                
! Missing number, treated as zero.
<to be read again> 
                   )
l.28 \includegraphics*[angle=0]{tmpdnuve0l3.eps}
                                                
! Undefined control sequence.
\Grot@start ...currentpoint translate \Grot@angle 
                                                  \GPT@space neg rotate neg ...
l.28 \includegraphics*[angle=0]{tmpdnuve0l3.eps}
                                                
! Extra }, or forgotten \endgroup.
\mbox #1->\leavevmode \hbox {#1}
                                
l.28 \includegraphics*[angle=0]{tmpdnuve0l3.eps}
                                                
! Too many }'s.
\@endfloatbox ...pagefalse \outer@nobreak \egroup 
                                                  \color@endbox 
l.29 \end{figure}
                 
! Extra \endgroup.
\color@endgroup ->\endgraf \endgroup 
                                     
l.29 \end{figure}
                 
! Too many }'s.
\color@endbox ->\color@endgroup \egroup 
                                        
l.29 \end{figure}
                 

! LaTeX Error: \begin{document} ended by \end{figure}.

See the LaTeX manual or LaTeX Companion for explanation.
Type  H <return>  for immediate help.
 ...                                              
                                                  
l.29 \end{figure}
                 
! Extra \endgroup.
<recently read> \endgroup 
                          
l.29 \end{figure}
                 
[1] (./tmpdnuve0l3.aux)

LaTeX Font Warning: Size substitutions with differences
(Font)              up to 7.12pt have occurred.

 )
(see the transcript file for additional information)
Output written on tmpdnuve0l3.dvi (1 page, 456 bytes).
Transcript written on tmpdnuve0l3.log.

Matplotlib version

  • Operating system: RedHatEnterpriseServer 7.3
  • Matplotlib version: '2.2.0'
  • Matplotlib backend (print(matplotlib.get_backend())): TkAgg
  • Python version:Python 3.6.4 |Anaconda, Inc.

Activity

  1. anntzer commented on May 13, 2018

    @anntzer
    Contributor

    I cannot reproduce the error (after adding text.usetex = True to the rcParams, which is clearly needed). Please provide the contents of your matplotlibrc (as given by matplotlib.matplotlib_fname()).

  2. added
    status: needs clarification
    on May 13, 2018
  3. nedlrichards commented on May 14, 2018

    @nedlrichards
    Author

    Thank you for looking into this. This seems to be specific to eps and ps, the figure saves fine as a pdf which I think will work for my current task. In the meantime, I have attached all uncommented lines of my matplotlibrc file.

    backend      : tkagg
    lines.linewidth   : 2.0     # line width in points
    font.size           : 26.0
    text.usetex         : True  # use latex for all text handling. The following fonts
    legend.numpoints     : 1      # the number of points in the legend line
    figure.figsize   : 12, 9    # figure size in inches
    

    Following your comment, I also recreated this issue with my MacOSX system. The matplotlibrc file on this system only has a font.size setting.

    Matplotlib version

    • Operating system: MacOSX 10.10.5
    • Matplotlib version: '2.2.0'
    • Matplotlib backend (print(matplotlib.get_backend())): MacOSX
    • Python version:Python 3.6.3 |Intel Corporation
  4. jklymak commented on May 14, 2018

    @jklymak
    Member

    I get this bug and didn't see an easy fix....

    % latex --version
    pdfTeX 3.14159265-2.6-1.40.18 (TeX Live 2017)
    kpathsea version 6.2.3
    Copyright 2017 Han The Thanh (pdfTeX) et al.
    There is NO warranty.  Redistribution of this software is
    covered by the terms of both the pdfTeX copyright and
    the Lesser GNU General Public License.
    For more information about these matters, see the file
    named COPYING and the pdfTeX source.
    Primary author of pdfTeX: Han The Thanh (pdfTeX) et al.
    Compiled with libpng 1.6.29; using libpng 1.6.29
    Compiled with zlib 1.2.11; using zlib 1.2.11
    Compiled with xpdf version 3.04
    
  5. added and removed
    status: needs clarification
    on May 14, 2018
  6. anntzer commented on May 14, 2018

    @anntzer
    Contributor

    Oh sorry, I was using mplcairo's postscript renderer, which works here :-) (for reasons I don't totally understand...)

  7. anntzer commented on May 16, 2018

    @anntzer
    Contributor

    I figured out the difference between matplotlib and mplcairo.

    In matplotlib, usetex is implemented in three different ways depending on the backend:

    1. agg compiles the tex to a dvi, converts the dvi to a png (with dvipng), and embeds the png as an image;
    2. pdf and svg extracts the individual glyphs from the dvi and re-embeds as glyphs into the pdf and svg;
    3. ps generates the rest of the image as postscript and embeds it using psfrags alongside the usetex text into a single tex file that gets compiled (as a consequence, that means that matplotlib's ps backend does not support using usetex for only some of the text objects, it's an all-or-nothing thing).
      Apparently the latter approach doesn't work with align (for a reason I still don't understand, though).

    mplcairo, on the other hand, uses approach 2) for all cases (because it can easily be made to work for all output formats, as they all need to know how to output individual glyphs anyways).

  8. anntzer commented on May 17, 2018

    @anntzer
    Contributor

    https://tex.stackexchange.com/questions/155699/how-to-use-display-equations-with-psfrag suggests to wrap the align* in a parbox. I think it's going to be very difficult to fix this (in Matplotlib's own PS backend) without a serious reworking of the PS backend.

  9. added
    Difficulty: Hard
    on May 17, 2018
  10. stecue commented on Apr 1, 2019

    @stecue

    I encountered this bug today and I need to send the figures as .eps format to my boss. Is there any workaround? I tried to wrap it with \parbox but the position in the .eps file is totally ruined...

  11. github-actions commented on May 6, 2023

    @github-actions

    This issue has been marked "inactive" because it has been 365 days since the last comment. If this issue is still present in recent Matplotlib releases, or the feature request is still wanted, please leave a comment and this label will be removed. If there are no updates in another 30 days, this issue will be automatically closed, but you are free to re-open or create a new issue if needed. We value issue reports, and this procedure is meant to help us resurface and prioritize issues that have not been addressed yet, not make them disappear. Thanks for your help!

  12. added
    status: inactive
    on May 6, 2023
  13. 4 remaining items

  14. removed
    status: closed as inactive
    on Jun 5, 2023
  15. added this to the future releases milestone on Jun 5, 2023
  16. github-actions commented on Jul 17, 2024

    @github-actions

    This issue has been marked "inactive" because it has been 365 days since the last comment. If this issue is still present in recent Matplotlib releases, or the feature request is still wanted, please leave a comment and this label will be removed. If there are no updates in another 30 days, this issue will be automatically closed, but you are free to re-open or create a new issue if needed. We value issue reports, and this procedure is meant to help us resurface and prioritize issues that have not been addressed yet, not make them disappear. Thanks for your help!

  17. added
    status: inactive
    on Jul 17, 2024
  18. tacaswell commented on Jul 17, 2024

    @tacaswell
    Member

    rcparams validation get a bit stricter, but

    import matplotlib
    import matplotlib.pyplot as plt
    
    params= {'text.latex.preamble' : r'\usepackage{amsmath}', 'text.usetex': True}
    plt.rcParams.update(params)
    
    fig, ax = plt.subplots(figsize=(8, 6))
    ax.text(0.5, 0.5, r'\begin{align*} H&: 2 \ \textrm{m} \\'\
                     + r'\Lambda &: 40 \ \textrm{m} \end{align*}',
             bbox=dict(boxstyle="square",
                       ec=(0.6, 0.6, 0.6),
                       fc=(1., 1., 1.),
                       ),
            fontsize=32)
    
    plt.show(block=False)
    # this works fine
    #plt.savefig('test.png', format='png')
    plt.savefig('test.eps', format='eps')

    still fails.

  19. removed
    status: inactive
    on Jul 18, 2024
  20. github-actions commented on Jul 18, 2025

    @github-actions

    This issue has been marked "inactive" because it has been 365 days since the last comment. If this issue is still present in recent Matplotlib releases, or the feature request is still wanted, please leave a comment and this label will be removed. If there are no updates in another 30 days, this issue will be automatically closed, but you are free to re-open or create a new issue if needed. We value issue reports, and this procedure is meant to help us resurface and prioritize issues that have not been addressed yet, not make them disappear. Thanks for your help!

  21. added
    status: inactive
    on Jul 18, 2025
  22. added
    status: closed as inactive
    on Aug 18, 2025
  23. added
    keep
    on Aug 18, 2025
  24. tacaswell commented on Aug 18, 2025

    @tacaswell
    Member

    Confirmed that this is still a bug.

  25. removed
    status: inactive
    status: closed as inactive
    on Aug 18, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Difficulty: Hardbackend: pskeepstatus: confirmed bugtopic: text/usetex

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions