# TikZ: How to scale the spy box with the tikzpicture?

With the help of How do I zoom a rectangle area in pgfplots adding a gray background even for the axis labels? and No content in zoom Tikz spy I have been able to get the most of what I want. Using stand alone this example looks likes this:

I have used the following "standalone" code to generate the picture.

% Source 1: http://tex.stackexchange.com/questions/102477/
% Source 2: http://tex.stackexchange.com/questions/62953/

\documentclass[tikz,border=2pt,png]{standalone}

\usepackage{pgfplots}
\pgfplotsset{compat=1.7} % Set the pgf plots to a current version
\usetikzlibrary{spy}

\begin{document}
\tikzset{new spy style/.style={spy scope={%
magnification=5,
size=1.25cm,
connect spies,
every spy on node/.style={
rectangle,
draw,
},
every spy in node/.style={
draw,
rectangle,
}
}
}
}
\begin{tikzpicture}[new spy style]
\begin{axis}[%
height=0.3\textwidth,
width=0.96\textwidth,
name = BG,
unbounded coords=jump,
scale only axis,
xmin=-3.68158764150225, xmax=4.05456770289782,
ymin=-1.44575077919192, ymax=1.15200357048622,
axis lines*=left,
axis equal image]
color=blue,
solid,
mark=+,
mark options={solid},
]
{sin(deg(x))};
color=red,
solid,
mark=*,
mark options={solid},
]
{sin(deg(x))+0.1};
color=green,
solid,
mark=x,
mark options={solid},
]
{sin(deg(x))-0.1};
\coordinate (spypoint) at (axis cs:0,0.0);
\coordinate (spyviewer) at (axis cs:1.7,-.5);

\end{axis}
%using axis coordinates and without "spy style" defined above
\spy[width=2cm,height=3cm] on (spypoint) in node [fill=white] at (spyviewer);

\end{tikzpicture}%
\end{document}


As you can see the I have been able to set the coordinates for \spy relative to the axis (near end of code). However I have not been able to define the size in the same way. As a consequence the graph may look different if used within a main document.

I am quite sure that this has to do with my use of "height" and "width" in the axis setup and/or the usage of "cm" in the \spy command.

My preferred solution would be something where I use the "\spy" in a way that I can refer to the coordinate system of the axis to determine its size as well. Any attempt of moving the "\spy" command inside the "axis" have so fare failed me.

The motivation behind this question can be seen form the following two images using my real data.

If compiled as standalone: And for comparison when compiled in the main document:

-

As the entire image is scaled by \textwidth I figured that it would be nice to also use this to scale \spy box. So replacing

\spy[width=2cm,height=3cm] on (spypoint) in node [fill=white] at (spyviewer);


with

\spy[width=0.2\textwidth,height=0.3\textwidth] on (spypoint) in node [fill=white] at (spyviewer);


was all that needed to be done. If the box is now placed and sized correctly in the standalone environment its size and position are preserved in the main document as well.

-