# pgfplots: How to adjust the width of the drawing area?

I want to produce plots that fit into the columns of a text document. My problem is that setting width=\linewidth seems to apply on the axis and labels only. When I put the legend outside it sticks out of the column:

I would like to get this:

In this case I have adjusted the width manually to fit the drawing area into the column (see code below).

Is there a way to achieve this automatically?

\documentclass[twocolumn]{article}
\usepackage[english]{babel}
\usepackage{blindtext}

\usepackage{pgfplots}
\pgfplotsset{compat=1.11}
\usetikzlibrary{backgrounds}

\begin{document}
%%% The following figure fits well %%%
\begin{figure}
\begin{tikzpicture}[show background rectangle,tight background]
\begin{axis}[
width = \linewidth,
xlabel=x axis label,
ylabel=y axis label,
legend pos = {north west},
]
\end{axis}
\end{tikzpicture}
\caption{This figure is part of a two column document and fits perfectly}
\end{figure}
\blindtext
%%% The next figure is to large %%%
\begin{figure}
\begin{tikzpicture}[show background rectangle,tight background]
\begin{axis}[
width = \linewidth,
xlabel=x axis label,
ylabel=y axis label,
legend pos = {outer north east},
]
\end{axis}
\end{tikzpicture}
\caption{Putting the legend outside the axis box leads to this unpleasant behavior.}
\end{figure}
\blindtext[5]
%%% The next figure is adjusted to fit %%%
\begin{figure}
\begin{tikzpicture}[show background rectangle,tight background]
\begin{axis}[
width = 0.76\linewidth, % This value only works for this plot
xlabel=x axis label,
ylabel=y axis label,
legend pos = {outer north east},
]
\end{axis}
\end{tikzpicture}
\caption{In this case the width has been adjusted manually so that plot and legend fit into the column.}
\end{figure}
\blindtext[5]
\end{document}


Package tikzscale is written for this purpose to automatically calculate the parameters to get the requested image size. The tikzpicture is stored in a separate file, e.g. \jobname-fig1.tikz and included via \includegraphics with key width:

\documentclass[twocolumn]{article}
\usepackage[english]{babel}
\usepackage{blindtext}

\usepackage{pgfplots}
\pgfplotsset{compat=1.11}
\usetikzlibrary{backgrounds}
\usepackage{tikzscale}
\usepackage{graphicx}
\usepackage{filecontents}

\begin{document}
\blindtext[5]
\begin{filecontents*}{\jobname-fig1.tikz}
\begin{tikzpicture}[show background rectangle,tight background]
\begin{axis}[
width = 0.76\linewidth, % This value only works for this plot
xlabel=x axis label,
ylabel=y axis label,
legend pos = {outer north east},
]