[Tex/LaTex] Background color in pgfplots that extends beyond the axis of the plot

backgroundspgfplots

I am interested in adding a background-color to my pgfplots plot that extends beyond the axis of the plot. See the image bellow for clarification; I am interested in adding a background color such as the plot in the image.

How would you achieve this?

enter image description here

Example from: The pgfplots manual (Christian Feuersänger, 2012, p. 20)

Best Answer

As Qrrbrbirlbel suggested, you might use the backgrounds library from TikZ. The example I provide you uses as predefined color the same one adopted in the pgfmanual and in the pgfplots documentation, but it can be easily changed via a specific key.

The code:

\documentclass[a4paper,11pt]{article}
\usepackage{pgfplots}
\pgfplotsset{width=7cm,compat=1.7}
\usetikzlibrary{backgrounds}
% background color definition from pgfmanual-en-macros.tex
\definecolor{graphicbackground}{rgb}{0.96,0.96,0.8}
% key to change color
\pgfkeys{/tikz/.cd,
  background color/.initial=graphicbackground,
  background color/.get=\backcol,
  background color/.store in=\backcol,
}
\tikzset{background rectangle/.style={
    fill=\backcol,
  },
  use background/.style={    
    show background rectangle
  }
}



\begin{document}
\begin{tikzpicture}[use background]
\begin{axis}
\addplot {sin(deg(x))};
\end{axis}
\end{tikzpicture}
\begin{tikzpicture}[background color=orange!20,use background]
\begin{axis}
\addplot+[only marks] {sin(deg(x))};
\end{axis}
\end{tikzpicture}
\end{document}

The result:

enter image description here