Skip to main content

LaTeX: Using gnuplot for Plotting Functions

$\mathrm{\LaTeX}$ has the capability to draw beautiful graphics. This feature is possible with TikZ package. Here is the plot of $f(x) = x$,

In $\mathrm{\LaTeX}$, everything has to be coded. From axes, to labels, to points on the $xy$-plane; that explains why four lines of codes, only for single, very simple plot.

To start sketching, one has to enclose the drawing inside the tikzpicture environment with options, for this case domain -- the domain of $x$. On second and third line, the codes draw the $x$ and $y$ axes; with usage,

options above is set to ->, which is the type of line, that is, with pointed end. (x1,y1) and (x2,y2) are cartesian coordinates for the line segment. Finally, the fourth line connects the $xy$-points: $\{(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5)\}$. As witnessed, $\mathrm{\LaTeX}$ has no capability when it comes to plotting functions, since one has to manually enter the points computed from the function to the draw output. However, $\mathrm{\LaTeX}$ can call external program and do the plotting. The said program is called gnuplot. This program has to be installed first, and then include this as option on $\mathrm{\LaTeX}$ compiler. For example on my pdflatex, I include this, --shell-escape. For Texmaker users, go to Options > Configure Texmaker, on PdfLaTeX insert --shell-escape. See photo below,

 
With this option, $\mathrm{\LaTeX}$ can finally call the gnuplot and do the computation on functions to obtain the $xy$-points that is needed by TikZ for plotting. For example, here are the plots of the functions: $f(x) = x; g(x) = x^2;$ and $h(x) = \sin(x)$.


 

The first four lines of the script are almost the same with the previous one above, except for the option, scale, which scales the $x$ and $y$ axes; and the second line, that draws the grid on the graph. The next four lines are loops, that generate the ticks of the two axes. Line 9, is a label for tick 0. The proceeding lines, plot the three functions. Unlike before, the $xy$-points are computed by the gnuplot, from the statement plot[id] function{...}.

Here are other examples taken from TikZ and PGF manual,





Comments