如何为图形的 y>0 区域着色

如何为图形的 y>0 区域着色

我有这张图,想用阴影标记出区域 $y\geq0$,以便读者能够看到它

\begin{center}
    \begin{tikzpicture}
        \begin{axis}[legend pos=outer north east,legend cell align=left,xlabel=$x$,ylabel=$y$,xmin=-5,xmax=5,ymin=-8,ymax=5,xtick distance=1,ytick distance=1,axis lines=center,yticklabels=\empty,yticklabels=\empty]
            \addplot[domain=-2:3, color=black,]{x^2-x-6};
            \addplot[domain=-2:-3, color=red,]{x^2-x-6};
            \addplot[domain=3:4, color=red,]{x^2-x-6};
            \draw [->, dashed] (900,800) -- (900,1200);
            \draw [->, dashed] (200,800) -- (200,1200);
        \end{axis}
    \end{tikzpicture}
\end{center}

我在 LaTeX 中见过许多阴影区域的例子,但我不知道如何改变它们来适应这个

答案1

试试这个代码:

\documentclass{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=newest}

\begin{document}
    \begin{tikzpicture}
            \begin{axis}[legend pos=outer north east,legend cell align=left,xlabel=$x$,ylabel=$y$,xmin=-5,xmax=5,ymin=-8,ymax=5,xtick distance=1,ytick distance=1,axis lines=center,yticklabels=\empty,yticklabels=\empty]
                \addplot[domain=-2:3, color=black,]{x^2-x-6};
                \addplot[domain=-2:-3, color=red,]{x^2-x-6};
                \addplot[domain=3:4, color=red,]{x^2-x-6};
                \filldraw[gray!20,opacity=.2] (-5,0.02) rectangle (5,8);
            \end{axis}
        
    \end{tikzpicture}
    
\end{document}

输出为:

在此处输入图片描述

您可以更改阴影的颜色和/或不透明度值。

答案2

代码

\documentclass{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=newest}
\pgfplotsset{
  add background rectangle y>0/.default=gray!20,
  add background rectangle y<0/.default=gray!20,
  add background rectangle y>0/.style={@add background rectangle={#1}{1}},
  add background rectangle y<0/.style={@add background rectangle={#1}{0}},
  @add background rectangle/.style 2 args={
    set layers, before end axis/.append code={
      \pgfonlayer{axis background}
        \fill[#1] ({rel axis cs:0,0}|-{axis cs:0,0}) rectangle (rel axis cs:1,#2);
      \endpgfonlayer}}}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
  add background rectangle y>0,           % ←
  add background rectangle y<0 = gray!40, % ←
  legend pos=outer north east, legend cell align=left,
  xlabel=$x$, ylabel=$y$, xmin=-5, xmax=5, ymin=-8, ymax=5,
  xtick distance=1, ytick distance=1, axis lines=center,
  yticklabels=\empty, yticklabels=\empty]
\addplot[domain=-2:3,  color=black] {x^2-x-6};
\addplot[domain=-2:-3, color=red]   {x^2-x-6};
\addplot[domain= 3:4,  color=red]   {x^2-x-6};
\end{axis}
\end{tikzpicture}
\end{document}

输出

在此处输入图片描述

相关内容