35

In the manual of PGFplots on page 333 the author describes how to position an axis environment relative to another axis environment:

\begin{tikzpicture}
    \begin{axis}[name=plot1,height=3cm,width=3cm]
        \addplot coordinates {(0,0) (1,1) (2,2)};
    \end{axis}
    \begin{axis}[name=plot2,at={($(plot1.east)+(1cm,0)$)},anchor=west,height=3cm,width=3cm]
         \addplot coordinates {(0,2) (1,1) (2,0)};
    \end{axis}
\end{tikzpicture}

Unfortunately, the same for scopes,

\begin{tikzpicture}
    \begin{scope}[name=scope1]
         \draw (1,2) rectangle (3,4);
    \end{scope}
    \begin{scope}[at={($(scope1.east)+(1cm,0)$)},anchor=west]
         \draw (5,6) rectangle (7,8);
    \end{scope}
\end{tikzpicture}

, does not work. How can I get it to work? I am not interested in absolute positioning, but merely in relative positioning.

Adriaan
  • 3,675
  • 2
  • 21
  • 41
  • What's the expected output? two squares side by side? – Tom Bombadil Nov 11 '13 at 14:49
  • @Adriaan -- wrap the the second case -- scope environment -- by axis environment and apply the same skill of the first case for the newly-wrapped axis environment. – Jesse Nov 11 '13 at 15:29

2 Answers2

46

Here is a solution using local bounding box to get the bounding box of the first scope and using shift to define the origin of the second scope:

\documentclass[tikz]{standalone}
\usetikzlibrary{calc}
\begin{document}
\begin{tikzpicture}
  \begin{scope}[local bounding box=scope1]
    \draw (2,2) rectangle (3,4);
  \end{scope}
  \begin{scope}[shift={($(scope1.east)+(1cm,0)$)}]
    \draw (0,0) rectangle (2,1);
  \end{scope}
\end{tikzpicture}
\end{document}

enter image description here

Paul Gaborit
  • 70,770
  • 10
  • 176
  • 283
13

Edit: the answer below is here for reference but note that nesting tikzpictures is discouraged due to some subtle side-effects that this may cause. In most cases, to build a "modular" picture you can use the pic action documented in Chapter 18 of the documentation. In simpler cases like the one in the question, a combination of shift and fit usually suffices.


If you need to keep the two scopes separated and wish to use them as "modules" I would suggest you use two nodes with nested tikzpictures as in

\begin{tikzpicture}
    \node(scope1){
        \begin{tikzpicture}
           \draw (1,2) rectangle (3,4);
        \end{tikzpicture}
    };
    \node[at={($(scope1.east)+(1cm,0)$)},anchor=west] (scope2){
        \begin{tikzpicture}
             \draw (5,6) rectangle (7,8);
        \end{tikzpicture}
    };
\end{tikzpicture}
Bordaigorl
  • 15,135
  • I would actually not propose to nest tikzpictures as this may bring some complications. –  Aug 13 '18 at 19:39