TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I want to write a macro, which takes a mathematical function as argument and returns a plot using pgfplots of the function and of its derivative.

I guess that this isn't possible using just LaTeX; however, for example, pgfplots can use the external program gnuplot to plot functions or there is LuaTeX...

So is there any way to get the derivative of a mathematical function do do this?

share|improve this question
You need to do it automatically? – R. M. Sep 24 '12 at 20:00
up vote 22 down vote accepted

Within reason (i.e. for not too nonlinear functions), you can numerically differentiate your functions right within PGFPlots, using the approach f'(x)=(f(x+dx)-f(x))/dx:


\begin{axis}[no markers, legend pos=south east, legend entries={Original function, Analytical derivative, Numerical derivative}]
\addplot [gray] {x^3};
\addplot [line width=3pt, red!50] {3*x^2};
\addplot [black] {((x+0.01)^3-(x)^3)/0.01};

\begin{axis}[no markers, samples=500]
\addplot [gray] {sin(deg(x))};
\addplot [line width=3pt, red!50] {cos(deg(x))};
\addplot [black] {(sin(deg(x+0.01))-sin(deg(x)))/0.01};

share|improve this answer
Nice! Is it possible to make a command \diff which takes the function as an argument and returns the differential quotient (with suitable small dx), then one would write for example: \addplot [black] {\diff{sin(x)}} which expands to \addplot [black] {(sin(deg(x+0.01))-sin(deg(x)))/0.01}; – student Sep 25 '12 at 7:54
I have added a feature request to add this to pgfmath: sourceforge.net/p/pgf/feature-requests/99 – student Jun 21 at 11:28

To derive a function analytically LaTeX is not really equipped with a linear algebra package. Instead you can use sympy, a python library for symbolic mathematics. An example session in python looks like this:

>>> from sympy import *
>>> x = Symbol('x')
>>> diff(sin(x), x)

Thanks to the great pythontex package this can easily be integrated into a LaTeX document. Have a look at the examples, which contain several derivatives of functions and plots using matplotlib. It is no problem though to adapt the output to pgfplots.

share|improve this answer
Wow, that's pretty nice! – Jake Sep 24 '12 at 18:47

the first 15 derivations of


which is

enter image description here


\def\getColor#1{\ifcase#1 Tan\or RedOrange\or magenta\or yellow\or green%
  \or Orange\or blue\or DarkOrchid\or BrickRed\or Rhodamine\or OliveGreen%
  \or Goldenrod\or Mahogany\or OrangeRed\or CarnationPink\or RoyalPurple\or Lavender\fi}


enter image description here

and the first 2 of sin(x)*cos(x)

enter image description here

share|improve this answer
Can we use pst-tools.pro's /factorial to define the function to be simpler? – kiss my armpit Sep 24 '12 at 20:20
sure, but not with the algebraic mode, because /factorial is a PS function – Herbert Sep 24 '12 at 20:23
\psPolynomial[coeff=0 0 1,Derivation=1]{-2}{4} from package pst-func – Herbert Feb 20 '13 at 15:24
not possible by automatic. If you want to plot it, then let it be calculated by \psTangentLine or use x dup add – Herbert Feb 20 '13 at 15:29
Is there a way to get the nodes (c,f(c)) in which f'(c)=0? – kiss my armpit Feb 20 '13 at 15:35

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.



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'''
    tikz = tikz.replace('tikz_args', tikz_args)
    tikz = tikz.replace('addplots', '\n'.join([func, func_deriv]))

\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)}


enter image description here

share|improve this answer
I get: ERROR: Undefined control sequence. --- TeX said --- l.115 \ProcessPgfPackageOptions {/PYTX/pkgopt} – student Sep 25 '12 at 8:10
@student That sounds like you may need to install the pgfopts package. – G. Poore Sep 25 '12 at 11:31
Now it compiles without output but without error. Do I need special compile options for this? – student Sep 25 '12 at 11:46
@student With pythontex, you have to compile, then run a Python script, then compile again to bring in the Python results. You need to install pythontex on your system according to the manual (see the section on installation and compiling). You may want to create a shortcut in your TeX editor for running the Python script. – G. Poore Sep 25 '12 at 12:12

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.