[Tex/LaTex] Filling area under a function

tikz-pgf

How to fill the area under a function using the package tikz? Only tikz. Is it possible?
This is what I have:

\begin{tikzpicture}
\draw[very thin, gray!30, step=1 cm](-4.9,-3.9) grid (4.9,3.9);

\draw [thick] [->] (-5,0)--(5,0) node[right, below] {$x$};
 \foreach \x in {-4,...,4}
   \draw[xshift=\x cm, thick] (0pt,-1pt)--(0pt,1pt) node[below] {$\x$};

\draw [thick] [->] (0,-4)--(0,4) node[above, left] {$y$};
 \foreach \y in {-3,...,3}
   \draw[yshift=\y cm, thick] (-1pt,0pt)--(1pt,0pt) node[left] {$\y$};

\draw [domain=-2:2, variable=\x] plot ({\x}, {\x*\x}) node[right] at (1.5,2) {$f(x)=x^2$};


\end{tikzpicture}

Please tell me, how do I fill the area under the function I drew? I mean the area between x axis and the curve.

Best Answer

The same plot command can be used to construct a path for the filled area:

\fill [gray, domain=-2:2, variable=\x]
  (-2, 0)
  -- plot ({\x}, {\x*\x})
  -- (2, 0)
  -- cycle;

Full example:

\documentclass{article}
\usepackage{tikz}

\begin{document}
  \begin{tikzpicture}
    \draw[very thin, gray!30, step=1 cm](-4.9,-3.9) grid (4.9,3.9);

    \fill [gray, domain=-2:2, variable=\x]
      (-2, 0)
      -- plot ({\x}, {\x*\x})
      -- (2, 0)
      -- cycle;

    \draw [thick] [->] (-5,0)--(5,0) node[right, below] {$x$};
     \foreach \x in {-4,...,4}
       \draw[xshift=\x cm, thick] (0pt,-1pt)--(0pt,1pt) node[below] {$\x$};

    \draw [thick] [->] (0,-4)--(0,4) node[above, left] {$y$};
     \foreach \y in {-3,...,3}
       \draw[yshift=\y cm, thick] (-1pt,0pt)--(1pt,0pt) node[left] {$\y$};

    \draw [domain=-2:2, variable=\x]
      plot ({\x}, {\x*\x}) node[right] at (1.5,2) {$f(x)=x^2$};

  \end{tikzpicture}
\end{document}

Result