[Tex/LaTex] Rectangle around data points in pgfplots

pgfplotstikz-pgf

If I have some data points in a pgfplot, how can I draw a rectangle around them, with the rectangle using the same coordinate system as the points?

I've included an example which does not work below.

\begin{tikzpicture}[scale=1.5]
\begin{axis}[xlabel=x, ylabel=y]
\addplot[smooth,mark=*,blue] plot coordinates {
    (0,2)
    (2,3)
    (3,1)
};
\addplot[red, thick,rounded corners] (0,-1) rectangle (0,0);
\end{axis}
\end{tikzpicture}

(Why is there a cross not a rectangle?)

From the manual I would expect that using:

\addplot[red, thick,rounded corners] (axis cs: 0,-1) rectangle (axis cs: 0,0);

might force the rectangle to use the same coordinate system as the points, but it does not, the code no longer compiles.

Best Answer

If you want to add elements like that to an axis, don't use \addplot (you're not adding a plot, after all), but \draw, \fill or \node:

 \documentclass[a4paper, 11pt]{article}

\usepackage{pgfplots}
\pgfplotsset{compat=newest} % Makes the axis label placement prettier

\begin{document}
\begin{tikzpicture}
\begin{axis}[xlabel=x, ylabel=y, ymin=0]
\addplot[smooth,mark=*,blue] plot coordinates {
    (0,2)
    (2,3)
    (3,1)
};
\draw [red, thick,rounded corners] (axis cs:-0.2,1.8) rectangle (axis cs:2.2,3.2);
\end{axis}
\end{tikzpicture}

\end{document}