Here's a PythonTeX version of @Jake's answer that uses pgfplots
. This required a reasonable bit of code to try to translate back and forth between Python and pgfplots
syntax. It might be simpler to use a Python plotting solution like matplotlib, though that might also require a little translation from SymPy.
\documentclass{article}
\usepackage{pgfplots}
\usepackage{pythontex}
\begin{document}
\begin{sympycode}
import re
x = Symbol('x')
def deriv(tikz_args, expr):
expr = eval(expr.replace('^', '**'))
expr_deriv = str(diff(expr, x)).replace('**', '^')
expr = str(expr).replace('**', '^')
for f in ['sin', 'cos', 'tan']:
if f in expr:
fpattern = f + r'\((.+)\)'
expr = re.sub(fpattern, f + r'(deg(\1))', expr)
if f in expr_deriv:
fpattern = f + r'\((.+)\)'
expr_deriv = re.sub(fpattern, f + r'(deg(\1))', expr_deriv)
func = r'\addplot [blue] {' + expr + r'};'
func_deriv = r'\addplot [red] {' + expr_deriv + r'};'
tikz = r'''
\begin{tikzpicture}
\begin{axis}[tikz_args]
addplots
\end{axis}
\end{tikzpicture}'''
tikz = tikz.replace('tikz_args', tikz_args)
tikz = tikz.replace('addplots', '\n'.join([func, func_deriv]))
print(tikz)
\end{sympycode}
\newcommand{\plotderiv}[2][]{\sympyc{deriv("#1", "#2")}}
\plotderiv[no markers, legend pos=south east, legend entries={Function, Derivative}]{x^3}
\plotderiv[no markers, legend pos=south east, legend entries={Function, Derivative}, samples=500]{sin(x)}
\end{document}