¿Cuál es la mejor manera para varias áreas bajo el gráfico de f(x)?

¿Cuál es la mejor manera para varias áreas bajo el gráfico de f(x)?

ingrese la descripción de la imagen aquí

El código:

\documentclass[dvipsnames]{article}
\usepackage{pgfplots}
\usetikzlibrary{babel,calc,backgrounds,quotes,angles,patterns,decorations.markings,intersections,arrows,arrows.meta}
\pgfplotsset{compat=newest}                       
\usepgfplotslibrary{fillbetween}

\begin{document}

\begin{tikzpicture}
  \begin{axis}[
                axis lines = middle,
                xmin = -1,
                ymin = -3,
                xmax = 6,
                ymax = 4,
                domain = -1:10,
                xtick = {1,2,...,5},
                ytick = \empty,
                xlabel style={below right},
                ylabel style={above left},
                x tick label style={below},
                xlabel = {$x$}, 
                ylabel = {$f$},
              ]    
              
    \addplot[very thick, color=Mahogany, domain=0:2, name path=p1] {3 - x};
    \addplot[very thick, color=Mahogany, domain=2:5, name path=p2] {3 - x};
    
    \addplot[domain=0:2, name path=x1] {0};
    \addplot[domain=2:5, name path=x2] {0};

    \addplot [fill=orange] fill between[of = p1 and x1];
    \addplot [fill=gray] fill between[of = p2 and x2];
  \end{axis}
\end{tikzpicture}

\end{document}

¿Existe otra forma (más elegante) de hacer este dibujo sin dividir la trama de 5-x en dos dominios? Y sin hacer x1 y x2 por cada parte.

Gracias de antemano.

Respuesta1

Puedes usar a soft clippara arreglar la restricción del dominio.

\documentclass[dvipsnames]{article}
\usepackage{pgfplots}
\usetikzlibrary{babel,calc,backgrounds,quotes,angles,patterns,decorations.markings,intersections,arrows,arrows.meta}
\pgfplotsset{compat=newest}                       
\usepgfplotslibrary{fillbetween}

\begin{document}

\begin{tikzpicture}
  \begin{axis}[
                axis lines = middle,
                xmin = -1,
                ymin = -3,
                xmax = 6,
                ymax = 4,
                domain = -1:10,
                xtick = {1,2,...,5},
                ytick = \empty,
                xlabel style={below right},
                ylabel style={above left},
                x tick label style={below},
                xlabel = {$x$}, 
                ylabel = {$f$},
              ]    
              
    \addplot[very thick, color=Mahogany, domain=0:5, name path=p1] {3 - x};
%    \addplot[very thick, color=Mahogany, domain=2:5, name path=p2] {3 - x};
    
    \addplot[domain=0:5, name path=x1] {0};
%    \addplot[domain=2:5, name path=x2] {0};

    \addplot [fill=orange] fill between[of = p1 and x1, soft clip={domain=0:2}];
    \addplot [fill=gray] fill between[of = p1 and x1, soft clip={domain=2:5}];
  \end{axis}
\end{tikzpicture}

\end{document}

ingrese la descripción de la imagen aquí

información relacionada