tikz-pgf,shading – How to Shade Regions Bounded by Several Curves in TikZ

shadingtikz-pgf

I know that my effort below can be improved upon considerably. In particular, there must be a way of shading the region in a single scope, as opposed to subdividing as I have done (thus necessitating a hidden gray boundary). Neither am I fond of sample points, but this is where my research has led me. Your constructive criticism is appreciated.

\documentclass{article}
\usepackage{tikz}
\begin{document}

\begin{tikzpicture}
%graph
\draw[draw=gray!50!white,fill=gray!50!white] 
    plot[smooth,samples=100,domain=0:1] (\x,{0}) -- 
    plot[smooth,samples=100,domain=1:0] (\x,{1});
\draw[fill=gray!50!white] plot[smooth,samples=100,domain=1:2.71828] (\x,{ln(\x)}) -- 
    plot[smooth,samples=100,domain=2.71828:1] (\x,{1});
\draw[domain=0:4] plot (\x,{1});
\draw[samples=100,domain=.25:4] plot (\x,{ln(\x)}) node[above left]{$y=\ln x$};
%coordinate grid
\draw (-.5,0)--(4.5,0) node[right]{$x$};
\draw (0,-1.5)--(0,2.5) node[above]{$y$};
\foreach \x in {1,2,3,4}
    \draw (\x,2pt)--(\x,-2pt) node[below] {$\x$};
\foreach \y/\ytext in {1,2}
    \draw (2pt,\y)--(-2pt,\y) node[left] {$\y$};    
%labels 
\node at (.75,.5) {$\mathcal{D}$};
\end{tikzpicture}

\end{document}

enter image description here

Best Answer

You can do many things only with clipping (if at all).

If you know the specific point you can do this in one entire path:

\draw[fill=gray!50] plot[smooth, samples=100, domain=1:e] (\x,ln \x) -| (0,0) -- cycle;

If you don’t know the points, you will need to use clip or even intersections.

Code

\documentclass[tikz]{standalone}
\tikzset{
  saveuse path/.code 2 args={
    \pgfkeysalso{#1/.style={insert path={#2}}}%
    \global\expandafter\let\csname pgfk@\pgfkeyscurrentpath/.@cmd\expandafter\endcsname
      % not optimal as it is now global through out the document
                           \csname pgfk@\pgfkeyscurrentpath/.@cmd\endcsname
    \pgfkeysalso{#1}},
  /pgf/math set seed/.code=\pgfmathsetseed{#1}}
\begin{document}
\tikz
  \draw[fill=gray!50] plot[smooth, samples=100, domain=1:e] (\x,ln \x) -| (0,0) -- cycle;
\begin{tikzpicture}
\begin{scope}
  \clip [saveuse path={plot path}{plot[smooth, samples=100, domain=.25:4] (\x, ln \x)}]
     -| (0,0) -- cycle;
  \clip[preaction={draw,fill=gray!50}] (0,0) rectangle (4,1);
\end{scope}
\draw [plot path];
\end{tikzpicture}
\begin{tikzpicture}
\begin{scope}[overlay]
  \clip [saveuse path={plot path}{plot[smooth, samples=100, domain=.25:4] (\x, ln \x)}]
     -- (0,5) -- (0,-5) -- cycle ;
  \clip [saveuse path={zigzag}{[math set seed=150, rounded corners=1.5pt] (0,3)
    \foreach \cnt in {1,...,8} {-- ++ (rnd, -.5*rnd)}}]
    [sharp corners] -- (0, -5) -- cycle;
  \clip (2,1) circle [radius=1.9] [draw, preaction={draw,fill=gray}];
\end{scope}
\draw [plot path, zigzag];
\end{tikzpicture}
\end{document}

Output

enter image description here

enter image description here enter image description here

Related Question