113

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

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

11 Answers 11

88

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$}
  ] 
    \addplot {x^2 - x +4}; 
  \end{axis}
\end{tikzpicture}
\end{document}

pgfplots drawing of f(x) = x^2 - x +4

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

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

pgfplots and gnuplot drawing of sin(x)

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

0
25

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}

enter image description here

3
  • 3
    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
    Commented Aug 31, 2015 at 18:34
  • 4
    @lblb Notice samples 7. Commented Aug 31, 2015 at 18:42
  • 3
    @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. Commented Aug 31, 2015 at 18:53
14

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

\documentclass{minimal}

\usepackage{pstricks-add}

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

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}
3
8

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

2
  • @xport: Only for completeness. I also prefer pgfplots. Commented May 31, 2011 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
    Commented Jan 17, 2013 at 1:38
8

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 sine plot

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...

7

xyplot is nice.

enter image description here

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.

1
  • For everyone looking for something like in the answer above: The following page might be interesting for you as well. It contains a lot of examples for how to generate different kinds of graph-theory/diagram graphs compiling even directly in Overleaf: texample.net/tikz/examples/tag/graphs
    – Daniel B.
    Commented Jan 19, 2021 at 15:11
6

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

0
6

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...

4
  • 5
    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. Commented Oct 2, 2010 at 11:57
  • 5
    (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
    Commented Apr 12, 2011 at 5:13
  • 1
    None of those reasons tell against using Sweave...
    – Seamus
    Commented Apr 15, 2011 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. Commented Sep 9, 2011 at 17:02
6

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.

5

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.

1
  • matplotlib 1.2 can export pgf
    – G. Poore
    Commented Nov 29, 2012 at 12:55

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .