# Best way to generate a nice function plots in LaTeX?

Which is the best way to put function plots into a LaTeX document?

• I think we need a bit more context here. Exactly what type of graph do you want? – Joseph Wright Sep 30 '10 at 18:42
• @Joseph Wright♦ Ok, how about $f(x)=\sin (1/x)/x$, -1<x<1. – AD. Sep 30 '10 at 18:46

To extend the answer from Mica, pgfplots can do calculations in TeX:

\documentclass{standalone}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
xlabel=$x$,
ylabel={$f(x) = x^2 - x +4$}
]
\end{axis}
\end{tikzpicture}
\end{document}


or using GNUplot (requires --shell-escape):

\documentclass{standalone}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
xlabel=$x$,
ylabel=$\sin(x)$
]
\end{axis}
\end{tikzpicture}
\end{document}


You can also pre-calculate values using another program, for example a spreadsheet, and import the data. This is all detailed in the manual.

With version 3 of PGF/TikZ the datavisualization library is available for plotting data or functions. Here are a couple of examples adapted from the manual (see part VI, Data Visualization).

\documentclass[border=2mm,tikz]{standalone}
\usepackage{tikz}
\usetikzlibrary{datavisualization}
\usetikzlibrary{datavisualization.formats.functions}
\begin{document}
\begin{tikzpicture}
\datavisualization [school book axes,
visualize as smooth line,
y axis={label={$y=x^2$}},
x axis={label} ]

data [format=function] {
var x : interval [-1.5:1.5] samples 7;
func y = \value x*\value x;
};
\end{tikzpicture}

\begin{tikzpicture}
\datavisualization [scientific axes=clean,
y axis=grid,
visualize as smooth line/.list={sin,cos,tan},
style sheet=strong colors,
style sheet=vary dashing,
sin={label in legend={text=$\sin x$}},
cos={label in legend={text=$\cos x$}},
tan={label in legend={text=$\tan x$}},
data/format=function
]
data [set=sin] {
var x : interval [-0.5*pi:4];
func y = sin(\value x r);
}
data [set=cos] {
var x : interval [-0.5*pi:4];
func y = cos(\value x r);
}
data [set=tan] {
var x : interval [-0.3*pi:.3*pi];
func y = tan(\value x r);
};
\end{tikzpicture}
\end{document}


• Is this just me or does the x² plot line look just a bit wonky? For example, the end regions (x=1.5 and x=–1.5) look to me as if the curve has zero curvature (so both ends look to end in a straight line which would be wrong for a parabola). I think this has to do with not enough plot points being used. Could it be that this package uses too few plot points and smooths them out afterwards, creating the wonky look? – lblb Aug 31 '15 at 18:34
• @lblb Notice samples 7. – Torbjørn T. Aug 31 '15 at 18:42
• @lblb And also visualize as smooth line. So in a way yes to your question, but only because that is what the library has been instructed to do. – Torbjørn T. Aug 31 '15 at 18:53

tikz + gnuplot (see the manual for details). Here's a "live" example used in a lecture (using beamer) to illustrate the convergence of a series of square-integrable functions.

\begin{tikzpicture}[domain=-1:1,yscale=2,xscale=4,smooth]
\fill[gray] (-1.2,-1.2) rectangle (1.2,2.5);
\draw[very thin] (-1.1,-1.1) grid[step=.5] (1.1,2.4);
\draw[thick,->] (-1.2,0) -- (1.2,0);
\draw[thick,->] (0,-1.2) -- (0,2.5);
\draw[color=red] plot[id=1] function{cos(pi*x)};
\draw<2->[color=blue,thick] plot[id=2] function{cos(pi*x)+cos(2*pi*x)/2};
\draw<3->[color=green!50!black,thick] plot[id=3] function{cos(pi*x) + cos(2*pi*x)/2 + cos(3*pi*x)/3};
\draw<4->[color=yellow,thick] plot[id=4] function{cos(pi*x) + cos(2*pi*x)/2 + cos(3*pi*x)/3 + cos(4*pi*x)/4};
\draw<5->[color=cyan,thick] plot[id=5] function{cos(pi*x) + cos(2*pi*x)/2 + cos(3*pi*x)/3 + cos(4*pi*x)/4 + cos(5*pi*x)/5};
\end{tikzpicture}

• texdoc tikz and lmgtfy.com/?q=gnuplot :) – Will Robertson Oct 1 '10 at 18:24
• I'm using LaTeX for years now and I did not know of texdoc. Will I go to jail? – Jill-Jênn Vie Oct 3 '16 at 10:27

OK, here's a non-TikZ answer for balance (you'd think TikZ is the second coming on SE!)

\documentclass{minimal}

\begin{document}
\psset{xunit=7cm,yunit=0.6cm}
\def\xlim{1}
\def\ylim{16}
\begin{pspicture*}(-\xlim,-\ylim)(\xlim,\ylim)
\psaxes[Dx=0.5,Dy=5]{<->}(0,0)(-\xlim,-\ylim)(\xlim,\ylim)
\psplot[plotpoints=500,showpoints=false,algebraic]{-1}{1}{sin(1/x)/x}
\end{pspicture*}
\end{document}

• Well, maybe not quite that but it certainly beats sliced bread. \usepackage{tikz} \usetikzlibrary{slice} \begin{document}\tikz \slice (bread) to (1cm);\end{document} – Loop Space Oct 1 '10 at 7:59
• @Andrew: there's something wrong with your example. It doesn't compile for me. – Will Robertson Oct 1 '10 at 8:19
• @Will: Do you have the latest bleeding edge version of TikZ? – Loop Space Oct 1 '10 at 9:00
• Erm, no... are you saying that TikZ does have sliced bread in it?! – Will Robertson Oct 1 '10 at 9:36
• Tikz is not the second coming, it's just a very naughty package... – Brent.Longborough Oct 1 '10 at 11:22

Further possibilities are pst-plot or Asymptote via the asymptote package. Not so good (because of less consistency) would be gnuplottex.

• @xport: Only for completeness. I also prefer pgfplots. – Thorsten Donig May 31 '11 at 18:49
• Asymptote has a nice package for graphs. Its main selling point over gnuplot to me is that you can use LaTeX freely in it (no jarring font mismatch) – vonbrand Jan 17 '13 at 1:38

Vincent Zoonekynd gives an example for this, from his long list of Metapost examples:

beginfig(166)
ux:=2mm;
uy:=5mm;
numeric xmin, xmax, ymin, ymax, M;
xmin := -6.3; xmax := 12.6;
ymin := -2;   ymax := 2;
M := 100;
draw (ux*xmin,0) -- (ux*xmax,0);
draw (0,uy*ymin) -- (0,uy*ymax);
pair a[];
for i=0 upto M:
a[i] := (
xmin + (i/M)*(xmax-xmin),
sind(180/3.14*( xmin + (i/M)*(xmax-xmin) ))
) xscaled ux yscaled uy;
endfor;
draw a[0] for i=1 upto M: --a[i] endfor;
endfig;


gives

This is much longer than the other examples, because it does everything from scratch, but it would be easy to put some functions for creating axes and scaling the graph, so that specifying the plot was some boilerplate plus the function definition. I might do that later...

Is there a specific reason you need to graph the function within LaTeX? wouldn't it be better to use something like R or matlab to generate a pdf that you can then \includegraphics ? This will generally speed up compilation, and graphs thus generated are probably more customisable and so on.

If you absolutely have to generate the graph inside LaTeX then consider using the standalone package: this will save some time when compiling big documents...

Then of course, there is sweave...

• Yes, there are good reasons for doing this within LaTeX: (a) less files to handle, (b) greater ease if you make edits, (c) possibility to conditionally change parameters in the plot. – Hendrik Vogt Oct 2 '10 at 11:57
• (d) The text in your graphics is handled by the same typesetting engine that is handling the text in your paper which makes it look cohesive, professional and very very sexy. – Sharpie Apr 12 '11 at 5:13
• None of those reasons tell against using Sweave... – Seamus Apr 15 '11 at 10:23
• Sweave seems like the natural answer. Less code, and once you learn it you're set up to do much more besides function graphs. – isomorphismes Sep 9 '11 at 17:02

R and sweave were already mentioned but I couldn't pass up the opportunity to mention tikzDevice (yes, again tikz). I have successfully been using it to generate .tex documents with R, for example

options(tikzLatex='/path to TeX distribution on computer' )
require(tikzDevice)
tikz("~/some destination/rgraph.tex", width = 5, height = 5.5)
Some R code
dev.off()


Usually I point it to the same folder as the working LaTeX document, and put it in the document

\input{rgraph}


I feel this gives me much needed control over my graphs, although I'll have to try some other solutions here before I decide which solution is the most comfortable for me. Just thought I'd add something (hopefully) of value.

The latest version of gnuplot itself also has a tikz output terminal

xyplot is nice.

edit: Oops — I thought you meant graph-theory graphs, not plots of ƒ(x) versus x. I would use R and Sweave to make the graphs in LaTeX.

Just to add to the mentioning of R and matlab, if you are familiar with Python, I would suggest the matplotlib library in conjunction with numPy. I use these (in addition to org-mode for emacs) all the time for publication quality plots.

• matplotlib 1.2 can export pgf – G. Poore Nov 29 '12 at 12:55