
我有以下內容:
\documentclass{article}
\usepackage{pgfplots}
\usepackage{mathtools}
\usepgfplotslibrary{fillbetween}
\usetikzlibrary{patterns}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
axis lines = middle,
xlabel = $x$,
ylabel = {$\begin{aligned}
\color{blue} f(x)& \color{blue}=1\\
\color {red} g(x)& \color{red}=|x|
\end{aligned}$}
]
\addplot [
name path = A,
domain=-2:2,
color=blue,
]
{1};
\addplot [
name path = B,
domain=-2:2,
color=red,
]
{abs(x))};
\addplot [
pattern=north west lines,
]
fill between [
of=A and B,
soft clip={domain=-1:1}
];
\end{axis}
\end{tikzpicture}
\end{document}
我的目標是在之間的區域內進行遮蔭
f(x) = 1
和
g(x) = |x|
圖形已繪製,但該區域沒有陰影。 (我正在使用 ShareLaTex)
答案1
(鄭重聲明:隨著 PGFPlots v1.16 的發布,您的範例給出了預期的結果。但是有一種更好/更簡單的方法來實現您想要的結果。)
而不是使用domain
use split
,它為您提供了 3 個可以單獨處理的段。因此,給出不填滿任何內容的常規選項 ( fill=none
),然後向「segment no 1
」樣式說明您想要的填滿圖案。 (這些段落從 0 開始計數,這就是為什麼數字 1 是您在這裡需要/想要的。)
% used PGFPlots v.1.14
\documentclass[border=5pt]{standalone}
\usepackage{pgfplots}
\usepackage{amsmath}
\usetikzlibrary{
patterns,
pgfplots.fillbetween,
}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
axis lines=middle,
xlabel=$x$,
ylabel={
$\begin{aligned}
\color{blue} f(x)& \color{blue}=1\\
\color {red} g(x)& \color{red}=|x|
\end{aligned}$
},
]
\addplot [
name path=A,
domain=-2:2,
color=blue,
] {1};
\addplot [
name path = B,
domain=-2:2,
color=red,
] {abs(x)};
\addplot [
fill=none,
] fill between [
of=A and B,
% --------------------------------------
% the below code is what I have changed
split,
% draw only selected ones:
% every segment no 0/.style: invisible
every segment no 1/.style={
pattern=north west lines,
},
% every segment no 2/.style: invisible
];
\end{axis}
\end{tikzpicture}
\end{document}
答案2
我認為這是fillbetween
.pgfplots
請注意,這只是我作為使用者的個人觀點,可能有特定的原因導致這種行為。
考慮下面的範例,其中我刪除了重現此行為不需要的所有部分。正如您的範例所示,該區域未填充。但是,如果您只是註解掉該axis lines=middle
行,該區域將按預期填充。
\documentclass{article}
\usepackage{pgfplots}
\usepgfplotslibrary{fillbetween}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
axis lines=middle,
domain=-2:2,
]
\addplot[name path=A,color=blue]{1};
\addplot[name path=B,color=red]{abs(x))};
\addplot[black] fill between[of=A and B,soft clip={domain=-1:1}];
\end{axis}
\end{tikzpicture}
\end{document}
0
啟用後處理該點似乎有問題axis lines=middle
。一個簡單的解決方法是使用一個fill between
from-1:0
和一個單獨的 from 0:1
。或者,使用split
Stefan Pinnow 提出的方法。
\addplot[pattern=north west lines] fill between[of=A and B,soft clip={domain=-1:0}];
\addplot[pattern=north west lines] fill between[of=A and B,soft clip={domain=0:1}];