如何根据轴正确放置物体?

如何根据轴正确放置物体?

我想在我的其中一张图表中放置一个矩形。但是我似乎混合了维度。有没有办法确保\draw使用相同的维度并填充当前“估计值”所包含的内容?

\documentclass[tikz]{standalone}

\usepackage{pgfplots}
\usepackage{verbatim}

\begin{document}
\centering

\begin{tikzpicture}
\begin{axis}[
            width=0.8\textwidth,
            height=0.4\textwidth,
    ]
    \addplot {-x};
        \addlegendentry{model}
    \addplot coordinates {
        (1,1)
        (1,2)
        (2,2)
        (2,1)
        (1,1)
    };
        \addlegendentry{estimate}
\end{axis}  

    \draw[fill=blue] (1,1) rectangle (2,2);
\end{tikzpicture}

\end{document}

答案1

将放置\draw在里面axis并使用axis cs坐标系,如\draw[fill=blue] (axis cs:1,1) rectangle (axis cs:2,2);

\documentclass[tikz]{standalone}

\usepackage{pgfplots}
\usepackage{verbatim}

\begin{document}
\centering

\begin{tikzpicture}
\begin{axis}[
            width=0.8\textwidth,
            height=0.4\textwidth,
    ]
    \addplot {-x};
        \addlegendentry{model}
    \addplot coordinates {
        (1,1)
        (1,2)
        (2,2)
        (2,1)
        (1,1)
    };
        \addlegendentry{estimate}
    \draw[fill=blue] (axis cs:1,1) rectangle (axis cs:2,2);
\end{axis}  


\end{tikzpicture}

\end{document}

相关内容