[Tex/LaTex] Why can’t I move the legend position with PGFPlots

legendpgfplots

I am trying to use PGFPlots to draw some graphics into my document, but I didn't manage to move the legend to the desired position. Here is the minimal code that I made:

\documentclass{article}
\usepackage{tikz}
\usepackage{pgfplots}


\begin{document}

\pgfplotsset{width=0.5*\textwidth}
\begin{tikzpicture}
    \begin{axis}[xlabel={$\theta_o$}]
        \addplot[mark=none, color=red] table{Figures/data1.txt};
        \addlegendentry{red}
        \addplot[mark=none, color=green] table{Figures/data2.txt};
        \addlegendentry{green}
        \addplot[mark=none, color=blue] table{Figures/data3.txt};
        \addlegendentry{blue}
   \end{axis}
\end{tikzpicture}

\end{document}

I'm getting this in my doc:

graph

The legend is over the data plot, so I want to move it from its current position to the top left corner. I tried the following command:

\begin{axis}[xlabel={$\theta_o$}][legend style={at={(0,1)},anchor=north west}]

so that the top left corner of the legend matches with the top left corner of the plot, but I got the same result again. I tried also with other values for the anchor or the at, but the legend didn't move.

What am I doing wrong?

Best Answer

Try

\documentclass{article}
\usepackage{pgfplots}


\begin{document}

\pgfplotsset{width=0.5*\textwidth}
\begin{tikzpicture}
    \begin{axis}[xlabel={$\theta_o$},
                 legend pos=south east]%or north west, ... ,outer north east
        \addplot[mark=none, color=red] coordinates {(0,0) (3,3)};
        \addlegendentry{red}
        \addplot[mark=none, color=green] coordinates {(0,1) (3,3)};
        \addlegendentry{green}
        \addplot[mark=none, color=blue]  coordinates {(0,2) (3,3)};
        \addlegendentry{blue}
   \end{axis}
\end{tikzpicture}

\end{document}

enter image description here

For positioning of legends see pgfplots manual, pp. 208 -- 209.