除给定形状外,在 pgfplots 中填充轴背景

除给定形状外,在 pgfplots 中填充轴背景

我想填充除给定圆圈之外的绘图轴的背景。我不想用白色填充绘图中的圆圈,因为此绘图将在背景可能不是白色的不同演示中重复使用。

我尝试了以下代码,但没有成功。

\documentclass{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.18}
\usetikzlibrary{calc}

\begin{document}
\begin{tikzpicture}
    \begin{axis}[%
        xmin=-4,%
        xmax=2.5,%
        ymin=-4,%
        ymax=2.5,%
        axis equal image,%
        xlabel={$x_1$},%
        ylabel={$x_2$},%
        axis background/.style={fill=black!10,even odd rule, insert path={(0,0) circle[radius=2^0.5]}},%
    ]
        \draw(axis cs:0,0) circle[radius=2^0.5];
        \draw[-latex] (axis cs:-1,-1) -- (axis cs:-3,-3) node[below right] {$\nabla c_1(x^{\ast})$};
        \draw[-latex] (axis cs:-1,-1) -- (axis cs:-2,-2) node[below right] {$\nabla f(x^{\ast})$};
        \addplot[red,mark=*,only marks] coordinates {(-1,-1)};
    \end{axis}
\end{tikzpicture}
\end{document}

有人在这次演讲中取得成功吗?我非常感谢你们提供的任何帮助。

答案1

此时,PGFPlots 不使用,axis:cs而在内部使用axis

\documentclass[border=1cm]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.18}
\usetikzlibrary{calc}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
xmin=-4, xmax=2.5,
ymin=-4, ymax=2.5,
axis equal image,
xlabel={$x_1$}, ylabel={$x_2$},
axis background/.style={fill=black!10, even odd rule, insert path={let \p1=(axis cs:0,0), \p2=(axis cs:0,{sqrt(2)}), \n1={veclen(\x2-\x1,\y2-\y1)}, in (\p1) circle[radius=\n1]}},
]
\draw(0,0) circle[radius=sqrt(2)];
\draw[-latex] (-1,-1) -- (-3,-3) node[below right] {$\nabla c_1(x^{\ast})$};
\draw[-latex] (-1,-1) -- (-2,-2) node[below right] {$\nabla f(x^{\ast})$};
\addplot[red,mark=*, only marks] coordinates {(-1,-1)};
\end{axis}
\end{tikzpicture}
\end{document}

除中心圆圈外的填充图形

答案2

尝试一下:

\documentclass{standalone}
\usepackage{pgfplots}
\usepgfplotslibrary{fillbetween}

\pgfplotsset{width=10cm,compat=1.15}

\pagestyle{empty}
\begin{document}
\begin{tikzpicture}
    \begin{axis}[%
        xmin=-4,%
        xmax=2.5,%
        ymin=-4,%
        ymax=2.5,%
        axis equal image,%
        xlabel={$x_1$},%
        ylabel={$x_2$},%
        axis background/.style={even odd rule, insert path={(0,0) circle[radius=2^0.5]}},%
 ]  
    
        \path[draw,red,name path=L1](current axis.south west) rectangle (current axis.north east);
        \draw[name path=L2](axis cs:0,0) circle[radius=2^0.5];
        \draw[-latex] (axis cs:-1,-1) -- (axis cs:-3,-3) node[below right] {$\nabla c_1(x^{\ast})$};
        \draw[-latex] (axis cs:-1,-1) -- (axis cs:-2,-2) node[below right] {$\nabla f(x^{\ast})$};
        \addplot[red,mark=*,only marks] coordinates {(-1,-1)};
        \addplot[blue!10] fill between[of=L1 and L2];
    \end{axis}
\end{tikzpicture}
\end{document}  

在此处输入图片描述

相关内容