Python - Diagramme mit Pythontex in Latex erstellen

Formelsatz für Mathematik, Naturwissenschaften und Technik


Panos13
Forum-Newbie
Forum-Newbie
Beiträge: 6
Registriert: Mi 21. Mär 2018, 14:23

Python - Diagramme mit Pythontex in Latex erstellen

Beitrag von Panos13 »

Hallo!

Ich bin neu hier und relativ neu mit Latex.
Ich versuche seit einigen Tagen ein Beispiel von Geoffrey M. Poore http://conference.scipy.org/proceedings ... _poore.pdf
laufen zu lassen, aber ich schaffe es nicht. Man kann ein Diagramm in Python erstellen, als pdf speichern und in ein Latex-Dokument einfügen.
Ich habe aber gelesen, dass man mit \pythontex von Poore alles im Latex-Dokument machen kann.
Ich finde im Internet keine ausführlichen Informationen wie das Ganze geht oder besser gesagt, ich blicke nicht durch.
Es heißt man kompiliert 3-mal:

- pdfLatex

- Pythontex (pythontex %.tex) - Ich bekomme folgendes:
Process started
C:\texlive\2017\bin\win32\runscript.tlu:711: command failed with exit code 1: python.exe c:\texlive \2017\texmf-dist\scripts\pythontex\pythontex.py Test1.tex
Process exited with error(s)

Ich habe es auch mit (pythontex.py %.tex) versucht - Ich bekomme folgendes:
Error : could not start the command : pythontex.py "Test1".tex

- pdfLatex

Beim ersten Mal bekomme ich die Datei *.pytxcode.
Beim zweiten wird der Ordner pythontex-files-* mit 3 Dateien und Fehler erstellt.
Und beim dritten wird kein gespeichertes Diagramm gefunden, weil keins da ist.
Etwas oder vieles mache ich falsch.
Ist möglich, dass das Ganze mit der Python Installation zu tun hat?!

Kann jemand helfen?
% Mein Latex-Dokument mit dem Beispiel von Poore.
\documentclass[]{scrreprt}

\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}	
\usepackage[ngerman]{babel}

\usepackage{amsmath}
\usepackage{graphicx}
%\usepackage{pgfplots}

\usepackage{pythontex}

\begin{document}

% Beispiel von Poore ----------------------------------------------------------
\begin{pylabcode}[plotsession]
	rc('text', usetex=True)
	rc('font', ** {'family':'serif', 'serif':['Times']})
	rc('font', size=10.0)
	rc('legend', fontsize=10.0)
	x = linspace(0, 3 * pi)
	figure(figsize=(3.25,2))
	plot(x, sin(x), label='$\sin(x)$')
	plot(x, sin(x) ** 2, label='$\sin^2(x)$',
		linestyle='dashed')
	xlabel(r'$x$-axis')
	ylabel(r'$y$-axis')
	xticks(arange(0, 4 * pi, pi), ('$0$',
		'$\pi$', '$2\pi$', '$3\pi$'))
axis([0, 3 * pi, -1, 1])
legend(loc='lower right')
savefig('myplot.pdf', bbox_inches='tight')
\end{pylabcode}

\begin{figure}
	\centering
	\includegraphics{myplot}
	\caption{\label{fig:matplotlib} A plot
			created with PythonTeX.}
\end{figure}
% ---------------------------------------------------------------------------------
\end{document}
Danke !

Stamm-

Simpler Plot

Beitrag von Stamm- »

Da das Beispiel weder auf »Overleaf« noch auf meinem System läuft und ich zudem keinerlei Erfahrung mit »pythontex« und Zeit zur Einarbeitung habe, kann ich nur eine (auf die Schnelle zusammengeschusterte) Lösung auf der Basis von »pgfplots« anbieten.
\documentclass[parskip=half,ngerman]{scrreprt}
\usepackage[T1]{fontenc}
\usepackage{selinput}
\SelectInputMappings{
  adieresis={ä},
  germandbls={ß}
}   
\usepackage{babel}

\usepackage{pgfplots}


\begin{document}
  \begin{figure}[!htb]
    \centering
    \begin{tikzpicture}
      \begin{axis}[
        width=10cm,
        height=7cm,
        xmin=0,
        xmax=3*pi,
        xtick={0,3.142,6.283,9.425},
        xticklabels={0\mathstrut,$\pi\mathstrut$,$2\pi\mathstrut$,$3\pi\mathstrut$},
        ymin=-1,
        ymax=1,
        domain=0:3*pi,
        samples=540,
        legend pos=south east,
        legend style={cells={anchor=west}}
      ]
        \addplot[blue,smooth] {sin(deg(x))};
        \addlegendentry{\( \sin(x) \)};
        \addplot[green!50!black,dashed] {sin(deg(x))^2};
        \addlegendentry{\( \sin^2(x) \)};       
      \end{axis}
    \end{tikzpicture}
    \caption{A plot created with »\textsf{pgfPlots}«}
    \label{fig:pgfplots}
  \end{figure}
\end{document}

Gast

Beitrag von Gast »

Bei mir funktioniert Dein Code prinzipiell, wenn ich die Einrückung korrigiere. Das Problem ist, dass Du das Bild myplot einbinden möchtest, dass aber im ersten Lauf noch gar nicht existiert. Die Datei wird erst im pythontex-Lauf erzeugt. Daher gibt das Fehlermeldungen.

Hier eine Variante ohne Fehlermeldungen
\documentclass[]{scrreprt}

\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}  
\usepackage[ngerman]{babel}

\usepackage{amsmath}
\usepackage{graphicx}
%\usepackage{pgfplots}

\usepackage{pythontex}

\begin{document}

% Beispiel von Poore ----------------------------------------------------------
\begin{pylabcode}[plotsession]
rc('text', usetex=True)
rc('font', ** {'family':'serif', 'serif':['Times']})
rc('font', size=10.0)
rc('legend', fontsize=10.0)
x = linspace(0, 3 * pi)
figure(figsize=(3.25,2))
plot(x, sin(x), label='$\sin(x)$')
plot(x, sin(x) ** 2, label='$\sin^2(x)$',
  linestyle='dashed')
xlabel(r'$x$-axis')  
ylabel(r'$y$-axis')
xticks(arange(0, 4 * pi, pi), ('$0$',
'$\pi$', '$2\pi$', '$3\pi$'))
axis([0, 3 * pi, -1, 1])
legend(loc='lower right')
savefig('myplot.pdf', bbox_inches='tight')
\end{pylabcode}

\begin{figure}
   \centering
   \IfFileExists{myplot.pdf}{\includegraphics{myplot}}{myplot.pdf noch nicht generiert!}
   \caption{\label{fig:matplotlib} A plot
         created with PythonTeX.}
\end{figure}
% ---------------------------------------------------------------------------------
\end{document}
Wenn die Datei test.tex heißt kompiliere sie mit
pdflatex test
pythontex test
pdfltatex test
Bei mir funktioniert das (MikTeX, Windows 10, Python 2.7.14) dann ohne Probleme.

Panos13
Forum-Newbie
Forum-Newbie
Beiträge: 6
Registriert: Mi 21. Mär 2018, 14:23

Beitrag von Panos13 »

Ich bedanke mich erstmal für die Lösung mit pgfplots.
Sie funktioniert und sieht gut aus.
Was Pythontex angeht.
pdflatex-Lauf: ohne Fehler
pythontex-Lauf: Process started
C:\texlive\2017\bin\win32\runscript.tlu:711: command failed with exit code 1:
python.exe c:\texlive\2017\texmf-dist\scripts\pythontex\pythontex.py Test1.tex
Process exited with error(s)
pdflatex-Lauf: ohne Fehler aber keine myplot.pdf
Ich benutze TexLive, Windows 10 und Python 3.6.4 (Anaconda3 5.1.0)
Ich versuche es mit Python 2.7.14 und melde mich wieder.

Danke

Gast

Beitrag von Gast »

Ah. Gibt es irgendeine Möglichkeit, mehr Fehlermeldungen von dem fehlschlagenden pythontex-Lauf zu bekommen? Vielleicht indem Du über die Kommandozeile kompilierst?

Panos13
Forum-Newbie
Forum-Newbie
Beiträge: 6
Registriert: Mi 21. Mär 2018, 14:23

Beitrag von Panos13 »

Ja, hier die Fehlermeldungen
------------------------------------------------------------------------------------------
C:\Users\PO\Documents\1_BACHELOR_TIMI\6_BabelGermanThesisPO\Test_Python1>pythontex Test1.tex
This is PythonTeX 0.16
---- Messages for pylab:plotsession:default ----
Traceback (most recent call last):
* PythonTeX stderr - error on line 32:
File "pythontex-files-test1\pylab_plotsession_default.py", line 66, in <module>
savefig('myplot.pdf', bbox_inches='tight')
File "C:\ANACONDA\lib\site-packages\matplotlib\pyplot.py", line 710, in savefig
res = fig.savefig(*args, **kwargs)
File "C:\ANACONDA\lib\site-packages\matplotlib\figure.py", line 2035, in savefig
self.canvas.print_figure(fname, **kwargs)
File "C:\ANACONDA\lib\site-packages\matplotlib\backend_bases.py", line 2212, in print_figure
**kwargs)
File "C:\ANACONDA\lib\site-packages\matplotlib\backends\backend_pdf.py", line 2586, in print_pdf
self.figure.draw(renderer)
File "C:\ANACONDA\lib\site-packages\matplotlib\artist.py", line 55, in draw_wrapper
return draw(artist, renderer, *args, **kwargs)
File "C:\ANACONDA\lib\site-packages\matplotlib\figure.py", line 1475, in draw
renderer, self, artists, self.suppressComposite)
File "C:\ANACONDA\lib\site-packages\matplotlib\image.py", line 141, in _draw_list_compositing_images
a.draw(renderer)
File "C:\ANACONDA\lib\site-packages\matplotlib\artist.py", line 55, in draw_wrapper
return draw(artist, renderer, *args, **kwargs)
File "C:\ANACONDA\lib\site-packages\matplotlib\axes\_base.py", line 2607, in draw
mimage._draw_list_compositing_images(renderer, self, artists)
File "C:\ANACONDA\lib\site-packages\matplotlib\image.py", line 141, in _draw_list_compositing_images
a.draw(renderer)
File "C:\ANACONDA\lib\site-packages\matplotlib\artist.py", line 55, in draw_wrapper
return draw(artist, renderer, *args, **kwargs)
File "C:\ANACONDA\lib\site-packages\matplotlib\axis.py", line 1192, in draw
renderer)
File "C:\ANACONDA\lib\site-packages\matplotlib\axis.py", line 1130, in _get_tick_bboxes
extent = tick.label1.get_window_extent(renderer)
File "C:\ANACONDA\lib\site-packages\matplotlib\text.py", line 922, in get_window_extent
bbox, info, descent = self._get_layout(self._renderer)
File "C:\ANACONDA\lib\site-packages\matplotlib\text.py", line 300, in _get_layout
ismath=False)
File "C:\ANACONDA\lib\site-packages\matplotlib\backends\backend_pdf.py", line 2148, in get_text_width_height_descent
renderer=self)
File "C:\ANACONDA\lib\site-packages\matplotlib\texmanager.py", line 501, in get_text_width_height_descent
dvifile = self.make_dvi(tex, fontsize)
File "C:\ANACONDA\lib\site-packages\matplotlib\texmanager.py", line 362, in make_dvi
with Locked(self.texcache):
File "C:\ANACONDA\lib\site-packages\matplotlib\cbook\__init__.py", line 2527, in __enter__
raise self.TimeoutError(err_str)
matplotlib.cbook.TimeoutError: LOCKERROR: matplotlib is trying to acquire the lock
'C:/Users/PO\\.matplotlib\\tex.cache\\.matplotlib_lock-*'
and has failed. This maybe due to any other process holding this
lock. If you are sure no other matplotlib process is running try
removing these folders and trying again.
--------------------------------------------------
PythonTeX: Test1 - 1 error(s), 0 warning(s)
C:\texlive\2017\bin\win32\runscript.tlu:711: command failed with exit code 1:
python.exe c:\texlive\2017\texmf-dist\scripts\pythontex\pythontex.py Test1.tex
C:\Users\PO\Documents\1_BACHELOR_TIMI\6_BabelGermanThesisPO\Test_Python1>

Panos13
Forum-Newbie
Forum-Newbie
Beiträge: 6
Registriert: Mi 21. Mär 2018, 14:23

Beitrag von Panos13 »

Nach einigen Änderungen (Python-Installation) habe ich jetzt folgende Fehler:

C:\Users\PO\Documents\1_BACHELOR_TIMI\6_BabelGermanThesisPO\Test_Python1>pythontex Test1.tex
This is PythonTeX 0.16

---- Messages for pylab:plotsession:default ----
Traceback (most recent call last):
* PythonTeX stderr - error on line -1:
File "pythontex-files-test1\pylab_plotsession_default.py", line 33, in <module>
from pylab import *
File "C:\ANACONDA\lib\site-packages\pylab.py", line 1, in <module>
from matplotlib.pylab import *
ModuleNotFoundError: No module named 'matplotlib.pylab'

--------------------------------------------------
PythonTeX: Test1 - 1 error(s), 0 warning(s)

C:\texlive\2017\bin\win32\runscript.tlu:711: command failed with exit code 1:
python.exe c:\texlive\2017\texmf-dist\scripts\pythontex\pythontex.py Test1.tex

C:\Users\PO\Documents\1_BACHELOR_TIMI\6_BabelGermanThesisPO\Test_Python1>

Gast

Beitrag von Gast »

Mhh, hast Du alle nötigen Module (matplotlib, numpy, ...) installiert? Hab leider nicht so viel Ahnung von Python. Vielleicht musst Du da mal einen Experten befragen.

Panos13
Forum-Newbie
Forum-Newbie
Beiträge: 6
Registriert: Mi 21. Mär 2018, 14:23

Beitrag von Panos13 »

Ich bin eigentlich Python - Anfänger.
Matplotlib habe ich schon. Ich recherchiere weiter und eventuell werde ich Python deinstallieren und dann nochmal mit den einzelnen Paketen installieren.
Die Fehler hängen höchstwahrscheinlich mit der Pythoninstallation zusammen.

Ich bedanke mich sehr für die Mühe.

Panos13
Forum-Newbie
Forum-Newbie
Beiträge: 6
Registriert: Mi 21. Mär 2018, 14:23

Beitrag von Panos13 »

C:\Users\PO\Documents\1_BACHELOR_TIMI\6_BabelGermanThesisPO\Test_Python1>pythontex Test1.tex
This is PythonTeX 0.16
--------------------------------------------------
PythonTeX: Test1 - 0 error(s), 0 warning(s)

Also, es klappt!
Ich habe die 3.6 Python Version deinstalliert und die 2.7 Version installiert.
Nach anfänglicher Frustration und längerem hin und her, hat auf einmal
nach einem Restart des Computers alles funktioniert!
Warum jetzt alles OK ist, was ich nicht.
Ich vermute das ganze hängt mit den einzelnen Schritten der Python - Installation
zusammen und nicht mit der Python - Version.
?

Antworten