Simple plot with pgfplots and LaTeX

hochl picture hochl · Feb 9, 2011 · Viewed 7.9k times · Source

I've just been searching like an hour on how to draw a simple function in LaTeX, for example f(x)=x^2. The examples I've tried did not work for some unknown reason, most probably because pdflatex would not start gnuplot (the -enable-xxx options do not work), but I found a LaTeX package that works: pgfplots. The only problem is that the documentation does not contain a simple example like what I need. Yes, if I wanted to draw complex diagrams with whatnot then I might find something, but a really simple example of a function -- no luck! But maybe I just need new glasses. So please, I'd be glad to get a simple example of a function plot in LaTeX, with an x and y axis and a graph!

EDIT: I've found this the best solution so far, but I'm not yet satisfied, for example the x label is in the middle. I really just want a standard plot without any fancy colors or 3d or similar.

\begin{tikzpicture}
\begin{axis}[
    axis x line=bottom,
    axis y line=middle,
    xlabel=$x$,
    ylabel={$x^2$},
    xmin=-4, xmax=4,
    ymin=0, ymax=4,
    width=0.8\textwidth,
    height=5cm
]
\addplot[mark=noner,smooth,domain=-1:1]{x^2};
\end{axis}
\end{tikzpicture}

Answer

Philipp picture Philipp · Feb 10, 2011

For simple functions you don't need Gnuplot, pgfplots is able to do the calculations in LaTeX. See the examples in section 4.2.4 of the pgfplots manual; the first example draws the function xx² − 4.