绝对值函数和 x 轴之间的填充

绝对值函数和 x 轴之间的填充

我正在尝试在给定间隔内对绝对值函数和 x 轴之间的区域进行着色。它对一个方程有效,但对另一个方程无效。有人能帮忙解决这个问题吗?

\documentclass[10pt]{article}
\usepackage{pgfplots,tikz}
\usepgfplotslibrary{fillbetween}
\pgfplotsset{compat=newest}
\begin{document}

\begin{tikzpicture}
  \begin{axis}%
    [grid=both,
     minor tick num=3,
     grid style={line width=.1pt, draw=gray!10},
     major grid style={line width=.2pt,draw=gray!50},
     axis lines=middle,
     enlargelimits={abs=0.5},
     xmin=-3, xmax=3
    ]
    \addplot[domain=-2.001:3,samples=100,smooth,blue, very thick, name path=A] {abs(2*x)-1}; 
    \addplot[draw=none,name path=B] {0};    
    \addplot[blue!15!white] fill between[of=A and B,soft clip={domain=-2:3}];     
  \end{axis}
\end{tikzpicture}

\begin{tikzpicture}
  \begin{axis}%
    [grid=both,
     minor tick num=3,
     grid style={line width=.1pt, draw=gray!10},
     major grid style={line width=.2pt,draw=gray!50},
     axis lines=middle,
     enlargelimits={abs=0.5},
     xmin=0, xmax=8
    ]
    \addplot[domain=0:8, samples=100,smooth,blue, very thick, name path=A] {2-abs(x-5)}; 
    \addplot[draw=none,name path=B] {0};    
    \addplot[blue!15!white] fill between[of=A and B,soft clip={domain=0:8}];     
  \end{axis}
\end{tikzpicture}

\end{document}

是什么原因导致第二张图表出现奇怪的阴影问题? 在此处输入图片描述

答案1

像这样?

在此处输入图片描述

您需要domain为两条路径定义,即为AB。更简单的方法是在axis序言中定义它:

\documentclass{article}
\usepackage{pgfplots}
\usepgfplotslibrary{fillbetween}
\pgfplotsset{compat=1.16}

\begin{document}
\begin{tikzpicture}
  \begin{axis}%
    [grid=both,
     minor tick num=3,
     grid style={line width=.1pt, draw=gray!10},
     major grid style={line width=.2pt,draw=gray!50},
     axis lines=middle,
     enlargelimits={abs=0.5},
     xmin=-3, xmax=3,
     domain=-2:3,samples=100  % <----
    ]
    \addplot[blue, very thick, name path=A] {abs(2*x)-1};
    \addplot[draw=none,name path=B] {0};
    \addplot[blue!15!white] fill between[of=A and B,soft clip={domain=-2:3}];
  \end{axis}
\end{tikzpicture}

\begin{tikzpicture}
  \begin{axis}%
    [grid=both,
     minor tick num=3,
     grid style={line width=.1pt, draw=gray!10},
     major grid style={line width=.2pt,draw=gray!50},
     axis lines=middle,
     enlargelimits={abs=0.5},
     xmin=0, xmax=8,
     domain=0:8, samples=100  % <----
    ]
    \addplot[blue, very thick, name path=A] {2-abs(x-5)};
    \addplot[draw=none,name path=B] {0};
    \addplot[blue!15!white] fill between[of=A and B,soft clip={domain=0:8}];
  \end{axis}
\end{tikzpicture}
\end{document}

相关内容