2

I am trying to fill the overlapping area between a rectangle and a function (a Gaussian in my case). I tried doing so using the approach outlined in the answer to this question:

\documentclass{article}
\usepackage{tikz}
\usepackage{pgfplots}
\pgfplotsset{compat=newest}

\begin{document}
  \pgfmathdeclarefunction{gauss}{2}{%
    \pgfmathparse{1/(#2*sqrt(2*pi))*exp(-((x-#1)^2)/(2*#2^2))}%
  }
  \usepgfplotslibrary{fillbetween}

  \begin{tikzpicture}
    \begin{axis}[xmin=0, xmax=2, ymin=0, ymax=1.8, axis x line=bottom, axis y line=left,
    ] 
      \filldraw [name path=rect, fill=green, draw=none, opacity=0.5] (0.5,0) rectangle (1.5,3);
      \addplot [name path=f, draw=none, mark=none, samples=200, smooth, fill=blue, opacity=0.5]{gauss(0.7,0.5)};
      \fill[red, intersection segments={of=rect and f}];
    \end{axis}
  \end{tikzpicture}
\end{document}

I don't understand why in my case only parts of the overlapping area are filled:

enter image description here

1 Answer 1

5

Adding the magic \closedcycle command:

\documentclass{article}
\usepackage{tikz}
\usepackage{pgfplots}
\pgfplotsset{compat=newest}

\begin{document}
  \pgfmathdeclarefunction{gauss}{2}{%
    \pgfmathparse{1/(#2*sqrt(2*pi))*exp(-((x-#1)^2)/(2*#2^2))}%
  }
  \usepgfplotslibrary{fillbetween}

  \begin{tikzpicture}
    \begin{axis}[xmin=0, xmax=2, ymin=0, ymax=1.8, axis x line=bottom, axis y line=left,
    ] 
      \filldraw [name path=rect, fill=green, draw=none, opacity=0.5] (0.5,0) rectangle (1.5,3);
      \addplot [name path=f, draw=none, mark=none, samples=200, smooth, fill=blue, opacity=0.5]{gauss(0.7,0.5)};
      \fill[red, intersection segments={of=rect and f}]\closedcycle;
    \end{axis}
  \end{tikzpicture}
\end{document}

enter image description here

2
  • Nice suggestion...+1
    – MadyYuvi
    Nov 21, 2019 at 12:47
  • Oh interesting! I tried that for the path of the Gaussian. What is \closedcycle doing in this case?
    – smonsays
    Nov 21, 2019 at 13:21

You must log in to answer this question.

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