I can see a few issues here:
You can't use \py{}
directly inside \addplot gnuplot
because it isn't fully expandable, so gnuplot gets literally \py{coeffA}
as its input and not the value of the coefficient.
The idea of defining \coeffA
and \coeffB
macros is good, but when you put the definitions inside the pycode
environment they don't work since pycode
doesn't typeset its contents (it doesn't return anything to LaTeX).
Even if you move the defs further, they won't appear in the document on the first run, so you'll have to do something about it. In the code below I just define them as some dummy values just to avoid the error report.
To make things easier to use, I've added some code which automatically iterates through all global numeric variables and creates corresponding LaTeX macros. Then their usage in the main document becomes as easy as \pyvar{varname}
.
The code:
\documentclass{article}
\usepackage[gobble=auto]{pythontex}
\usepackage{pgfplots}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\def\pyvar#1{\csname pythonvar@#1\endcsname}
\begin{pycode}
from numbers import Number
def exposeNumericGlobals():
res = r'\makeatletter '
d = globals()
for key in d.keys():
val = d[key]
if isinstance(val, Number):
res = res + (r'\gdef\pythonvar@%s{%s} ' % (key, val))
res = res + r'\makeatother'
return res
\end{pycode}
\AtBeginDocument{\py{exposeNumericGlobals()}}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{pycode}
from numpy import *
coeffA = 7
coeffB = sqrt(coeffA)
\end{pycode}
\begin{document}
\begin{tikzpicture}
\begin{axis}[xlabel=$x$,ylabel=$y$]
\addplot gnuplot {\pyvar{coeffA}*x**2 + \pyvar{coeffB}*x};
\end{axis}
\end{tikzpicture}
\end{document}
The output:
pysub
example in tex.stackexchange.com/a/65294/10742.