![绝对值函数和 x 轴之间的填充](https://linux22.com/image/409014/%E7%BB%9D%E5%AF%B9%E5%80%BC%E5%87%BD%E6%95%B0%E5%92%8C%20x%20%E8%BD%B4%E4%B9%8B%E9%97%B4%E7%9A%84%E5%A1%AB%E5%85%85.png)
我正在尝试在给定间隔内对绝对值函数和 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
为两条路径定义,即为A
和B
。更简单的方法是在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}