# Legends for scaled pgfplots

I am using the pgfplots package to create some plots of data for my thesis. As an example, consider the following code:

\documentclass[a4paper]{article}

\usepackage{tikz}
\usepackage{pgfplots}
\pgfplotsset{compat=1.8}

\begin{document}

\begin{tikzpicture}
\begin{semilogyaxis}[
xlabel=Cost,
ylabel=Gain]
(10,100)
(20,150)
(40,225)
(80,340)
(160,510)
(320,765)
(640,1150)
};

\end{semilogyaxis}
\end{tikzpicture}

\begin{tikzpicture}
\begin{semilogyaxis}[
xscale=1.5,
xlabel=Cost,
ylabel=Gain]
(10,100)
(20,150)
(40,225)
(80,340)
(160,510)
(320,765)
(640,1150)
};

\end{semilogyaxis}
\end{tikzpicture}

\end{document}


For each data set I want to add a corresponding legend entry which works fine if I use \addlegendentry. To better fit the plot on my page I am using occasionaly adding an xcale/yscale to my axis. I am only interested in the aspect ratio, since I am using the tikzscale package to scale my plots to the current \textwidth.

Unfortunately xscale/yscale does not seem to work properly with the legend entries (just render the example): If I scale down the y-axis, the legend entries are displayed above the plot, If I scale up the x-axis, the legend entries are far outside of the plot on the right side:

Is there anything I can do to obtain a desired aspect ratio with working legend entries?

You can position the legend using the rel axis coordinate system:

\documentclass[a4paper]{article}

\usepackage{tikz}
\usepackage{pgfplots}
\pgfplotsset{compat=1.8}

\pgfplotsset{every axis legend/.style={
cells={anchor=center},% Centered entries
inner xsep=3pt,inner ysep=2pt,nodes={inner sep=2pt,text depth=0.15em},
anchor=south east,
shape=rectangle,
fill=white,
draw=black,
at={(rel axis cs:0.98,0.02)}
}
}

\begin{document}

\begin{tikzpicture}
\begin{semilogyaxis}[
xlabel=Cost,
ylabel=Gain]
(10,100)
(20,150)
(40,225)
(80,340)
(160,510)
(320,765)
(640,1150)
};

\end{semilogyaxis}
\end{tikzpicture}

\begin{tikzpicture}
\begin{semilogyaxis}[
xscale=1.5,
xlabel=Cost,
ylabel=Gain]
(10,100)
(20,150)
(40,225)
(80,340)
(160,510)
(320,765)
(640,1150)
};