26

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.

2 Answers 2

31

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

14

This solution requires a recent version of the pgfplots package, >=1.10.

You could also use the plotting capabilities of the pgfplots package and its library fillbetween that lets you fill the area between two generic curves.

First, you draw the curve that you want to plot and you assign a name to it. Then, you insert the x axis as a “fictional” curve, that is actually plotted but not drawn, and you name it, too.

Finally, you shade the area below your curve issuing a third \addplot command.

\documentclass[border=5pt]{standalone}
\usepackage{pgfplots}
\usepgfplotslibrary{fillbetween}
\begin{document}
\begin{tikzpicture}
  \begin{axis}[
    axis lines=center,
    grid=major,
    ymin=-5,
    no marks,
    ]
    \addplot+[smooth,blue,name path=A] {x*x}; % actual curve
    \addplot+[draw=none,name path=B] {0};     % “fictional” curve
    \addplot+[gray] fill between[of=A and B,soft clip={domain=-4:4}]; % filling
  \end{axis}
\end{tikzpicture}
\end{document}

enter image description here

You must log in to answer this question.

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