# How can I place an inset inside a pgfplots axis using the parent axis coordinates?

I'd like to place an inset axis inside a parent axis with pgplots. The position, width and height of the inset axis should be specified using the data coordinates of the parent axis. This is what I got so far:

\documentclass{article}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}
\begin{axis}[width=\textwidth,name=mainplot]
\coordinate (insetSW) at (axis cs:-4,2); % south west corner of inset
\coordinate (insetNE) at (axis cs:-2,4); % north east corner of inset
\end{axis}
\begin{axis}[at={(insetSW)},anchor=south west,name=inset]
\end{axis}
\end{tikzpicture}
\end{document}


The south west corner of the inset is at the correct position. How can I calculate the width and height of the inset, so that its north east corner is at insetNE?

Or, is it possible to specify the axis dimensions by providing two coordinates to \begin{axis}[..]?

One possible solution is to cacluate width and height by the given coordinates inside a let statement. Then save the result of the calculation to a macro and use this macro when creating the inset axis. Here is a MWE:

\documentclass{article}
\usepackage{pgfplots}
\usetikzlibrary{calc}
\begin{document}
\begin{tikzpicture}
\pgfkeys{/tikz/savenumber/.code 2 args={\global\edef#1{#2}}}
\begin{axis}[width=200pt,name=mainplot,xtick={-4,0},ytick={2,6},grid]
\coordinate (insetSW) at (axis cs:-4,2); % south west corner of inset
\coordinate (insetNE) at (axis cs:0,6); % north east corner of inset
\path
let
\p1 = (insetSW),
\p2 = (insetNE),
\n1 = {(\x2 - \x1)},
\n2 = {(\y2 - \y1)}
in
[savenumber={\insetwidth}{\n1},savenumber={\insetheight}{\n2}];
\end{axis}
\begin{axis}[
at={(insetSW)}, anchor=south west, name=inset, width=\insetwidth,
height=\insetheight, xticklabels={}, yticklabels={}, scale only axis]
\end{axis}
\end{tikzpicture}

% DEBUG
inset width: \insetwidth,
inset height: \insetheight,
\end{document}


Which produces

The inset has the desired position with the lower left corner at (-4,2) and the upper right corner at (0,6). The tick labels of the inset axis have been removed to prevent a width/height is too small... error. The key scale only axis has to be provided to the inset axis, so that the axis exactly matches the desired dimensions.