Импорт siunitx в Python - PullRequest
0 голосов
/ 26 марта 2020

Я пытаюсь импортировать пакет 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 и как я могу заставить его работать должным образом?

1 Ответ

0 голосов
/ 26 марта 2020

Вид этого дал мне идею: я вставил строку

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

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...