# [Tex/LaTex] How to put legend below the chart

legendpgfplots

I have the following code that produces a line chart:

\begin{figure}[p]
\centering
\begin{tikzpicture}
\begin{axis}[
use units,
cycle list name=exotic, %This defines the color. It produces nicer colors
width=15cm, height=8cm,     % size of the image
grid = major,
grid style={dashed, gray!30},
%xmode=log,log basis x=10,
%ymode=log,log basis y=10,
xmin=0,     % start the diagram at this x-coordinate
ymin=0,     % start the diagram at this y-coordinate
%/pgfplots/xtick={0,5,...,60}, % make steps of length 5
%extra x ticks={23},
%extra y ticks={0.507297},
axis background/.style={fill=white},
ylabel=Time,
xlabel=Number of Datapoints (n),
y unit=s,y unit prefix=m,
tick align=outside]

% import the correct data from a CSV file
\addplot table [col sep=comma,trim cells=true,y=Best Case (Ascending)] {datasets/time_mergesort.txt};
\addplot table [col sep=comma,trim cells=true,y=Average Case (Random)] {datasets/time_mergesort.txt};
\addplot table [col sep=comma,trim cells=true,y=Worst Case (Descending)] {datasets/time_mergesort.txt};
\legend{Ascending,Random,Descending}
\end{axis}
\end{tikzpicture}
\caption{Mergesort Run Time for Sorting Random Data}
\label{fig:merge_sort_from_csv}
\end{figure}


And at the moment the legend appears on the chart on the upper right corner. I need to move that below the chart, or even to leave that on the chart but to move that on the upper left corner.

I have tried the solution mentioned at this question, but it did not work for me.

How can I move the axis in a different position?

#### Best Answer

pgfplots defines several shortcut legend pos settings, as defined in Section 4.9.5 of its manual; here you could choose legend pos=north west or legend pos=outer north east, which is currently the only pre-defined legend position outside the axis box.

If you want to place it in any other location, the legend pos keys are just shorthand for

legend style={at={(<x>,<y>)},anchor=<name>}


where <x> and <y> are in terms of the rel axis cs (ranges from 0 to 1 over the width and height of the axis box.

Here are a few possibilities:

\documentclass[tikz]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.12}

\begin{document}
\begin{tikzpicture}
\begin{axis}[legend pos=north west]
\addplot {x};
\addlegendentry{$x$}
\addplot {x^2};
\addlegendentry{$x^2$}
\end{axis}
\end{tikzpicture}

\begin{tikzpicture}
\begin{axis}[legend pos=outer north east]
\addplot {x};
\addlegendentry{$x$}
\addplot {x^2};
\addlegendentry{$x^2$}
\end{axis}
\end{tikzpicture}

\begin{tikzpicture}
\begin{axis}[legend style={at={(0.5,-0.1)},anchor=north}]
\addplot {x};
\addlegendentry{$x$}
\addplot {x^2};
\addlegendentry{$x^2$}
\end{axis}
\end{tikzpicture}
\end{document}