将siunitx导入Python

问题描述 投票:0回答:1

我正在尝试将siunitx Latex软件包导入Python(版本3.7),以便在标记轴时使用更清晰的符号。

这是我的代码:

import matplotlib.pylab as plt
import matplotlib as mpl
import numpy as np

pgf_with_latex = {                      # setup matplotlib to use latex for output
    "pgf.texsystem": "pdflatex",        # change this if using xetex or lautex
    "text.usetex": True,                # use LaTeX to write all text
    "pgf.preamble": [
        r"\usepackage[utf8x]{inputenc}",    # use utf8 fonts 
        r"\usepackage[T1]{fontenc}",        # plots will be generated
        r"\usepackage{siunitx}",
        ]                                   # using this preamble
    }

mpl.rcParams.update(pgf_with_latex)


x=np.linspace(1,100,10)
y=x
plt.plot(x, y)
plt.title(r"Disctances given in [\si{\metre}]")

和我收到的错误:

runfile('C:/Users/bobra/Desktop/untitled2.py', wdir='C:/Users/bobra/Desktop')
Traceback (most recent call last):

  File "C:\Users\bobra\Anaconda3\Lib\site-packages\matplotlib\texmanager.py", line 304, in _run_checked_subprocess
    stderr=subprocess.STDOUT)

  File "C:\Users\bobra\Anaconda3\lib\subprocess.py", line 411, in check_output
    **kwargs).stdout

  File "C:\Users\bobra\Anaconda3\lib\subprocess.py", line 512, in run
    output=stdout, stderr=stderr)

CalledProcessError: Command '['latex', '-interaction=nonstopmode', '--halt-on-error', 'C:\\Users\\bobra\\.matplotlib\\tex.cache\\f37855bf2bbf60cd1cb0626b39b0b8c3.tex']' returned non-zero exit status 1.


The above exception was the direct cause of the following exception:

Traceback (most recent call last):

  File "C:\Users\bobra\Anaconda3\Lib\site-packages\IPython\core\formatters.py", line 341, in __call__
    return printer(obj)

  File "C:\Users\bobra\Anaconda3\Lib\site-packages\IPython\core\pylabtools.py", line 248, in <lambda>
    png_formatter.for_type(Figure, lambda fig: print_figure(fig, 'png', **kwargs))

  File "C:\Users\bobra\Anaconda3\Lib\site-packages\IPython\core\pylabtools.py", line 132, in print_figure
    fig.canvas.print_figure(bytes_io, **kw)

  File "C:\Users\bobra\Anaconda3\Lib\site-packages\matplotlib\backend_bases.py", line 2065, in print_figure
    **kwargs)

  File "C:\Users\bobra\Anaconda3\Lib\site-packages\matplotlib\backends\backend_agg.py", line 527, in print_png
    FigureCanvasAgg.draw(self)

  File "C:\Users\bobra\Anaconda3\Lib\site-packages\matplotlib\backends\backend_agg.py", line 388, in draw
    self.figure.draw(self.renderer)

  File "C:\Users\bobra\Anaconda3\Lib\site-packages\matplotlib\artist.py", line 38, in draw_wrapper
    return draw(artist, renderer, *args, **kwargs)

  File "C:\Users\bobra\Anaconda3\Lib\site-packages\matplotlib\figure.py", line 1709, in draw
    renderer, self, artists, self.suppressComposite)

  File "C:\Users\bobra\Anaconda3\Lib\site-packages\matplotlib\image.py", line 135, in _draw_list_compositing_images
    a.draw(renderer)

  File "C:\Users\bobra\Anaconda3\Lib\site-packages\matplotlib\artist.py", line 38, in draw_wrapper
    return draw(artist, renderer, *args, **kwargs)

  File "C:\Users\bobra\Anaconda3\Lib\site-packages\matplotlib\axes\_base.py", line 2607, in draw
    self._update_title_position(renderer)

  File "C:\Users\bobra\Anaconda3\Lib\site-packages\matplotlib\axes\_base.py", line 2556, in _update_title_position
    if title.get_window_extent(renderer).ymin < top:

  File "C:\Users\bobra\Anaconda3\Lib\site-packages\matplotlib\text.py", line 890, in get_window_extent
    bbox, info, descent = self._get_layout(self._renderer)

  File "C:\Users\bobra\Anaconda3\Lib\site-packages\matplotlib\text.py", line 298, in _get_layout
    clean_line, self._fontproperties, ismath=ismath)

  File "C:\Users\bobra\Anaconda3\Lib\site-packages\matplotlib\backends\backend_agg.py", line 201, in get_text_width_height_descent
    s, fontsize, renderer=self)

  File "C:\Users\bobra\Anaconda3\Lib\site-packages\matplotlib\texmanager.py", line 448, in get_text_width_height_descent
    dvifile = self.make_dvi(tex, fontsize)

  File "C:\Users\bobra\Anaconda3\Lib\site-packages\matplotlib\texmanager.py", line 338, in make_dvi
    texfile], tex)

  File "C:\Users\bobra\Anaconda3\Lib\site-packages\matplotlib\texmanager.py", line 317, in _run_checked_subprocess
    exc=exc.output.decode('utf-8'))) from exc

RuntimeError: latex was not able to process the following string:
b'Disctances given in \\\\si{\\\\metre}'

Here is the full report generated by latex:
This is pdfTeX, Version 3.14159265-2.6-1.40.20 (TeX Live 2019/W32TeX) (preloaded format=latex)
 restricted \write18 enabled.
entering extended mode
(c:/Users/bobra/.matplotlib/tex.cache/f37855bf2bbf60cd1cb0626b39b0b8c3.tex
LaTeX2e <2020-02-02> patch level 5
L3 programming layer <2020-02-25>
(c:/texlive/2019/texmf-dist/tex/latex/base/article.cls
Document Class: article 2019/12/20 v1.4l Standard LaTeX document class
(c:/texlive/2019/texmf-dist/tex/latex/base/size10.clo))
(c:/texlive/2019/texmf-dist/tex/latex/type1cm/type1cm.sty)
(c:/texlive/2019/texmf-dist/tex/latex/base/textcomp.sty)
(c:/texlive/2019/texmf-dist/tex/latex/base/inputenc.sty)
(c:/texlive/2019/texmf-dist/tex/latex/geometry/geometry.sty
(c:/texlive/2019/texmf-dist/tex/latex/graphics/keyval.sty)
(c:/texlive/2019/texmf-dist/tex/generic/iftex/ifvtex.sty
(c:/texlive/2019/texmf-dist/tex/generic/iftex/iftex.sty))

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


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

) (c:/texlive/2019/texmf-dist/tex/latex/l3backend/l3backend-dvips.def)
(./f37855bf2bbf60cd1cb0626b39b0b8c3.aux)
*geometry* driver: auto-detecting
*geometry* detected driver: dvips
! Undefined control sequence.
l.14 ....000000}{\rmfamily Disctances given in \si
                                                  {\metre}}
No pages of output.
Transcript written on f37855bf2bbf60cd1cb0626b39b0b8c3.log.




<Figure size 432x288 with 1 Axes>

当我在代码中编写常规m而不是\si{\metre}时,它成功运行。

而且,当我放置一些与非Siunitx相关的LaTex输入时,例如plt.title(r"Disctances given in $[\AA]$"),我的代码也可以使用。

导入siunitx时我在做什么错,如何使它正常工作?

python matplotlib latex
1个回答
0
投票

[看到this给了我一个主意:我插入了行

mpl.use("pgf")

就在前面

mpl.rcParams.update(pgf_with_latex)

这使代码正常运行。

附带说明,检索图的唯一方法是使用plt.savefig,因为pgf不支持plt.show()

siunitx.py:23: UserWarning: Matplotlib is currently using pgf, which is a non-GUI backend, so cannot show the figure.
  plt.show()

siunitx demo

© www.soinside.com 2019 - 2024. All rights reserved.