I have several tikz pictures which only differ in one line. I want to reuse the parts that are always the same with \savebox (Source) but I keep getting errors. What's wrong?
MWE (without \savebox)
\documentclass[tikz]{standalone}
\begin{document}
\begin{tikzpicture}
\draw[step=1,help lines,black!20] (-0.99,-0.99) grid (8.99,8.99);
\draw[thick,->] (-1,0) -- (9,0) node[pos=0.97,below] {$x$};
\draw[thick,->] (0,-1) -- (0,9) node[pos=0.97,left] {$y$};
% Graph 1
\draw[very thick,color=black,domain=-1:9] plot (\x,{\x});
\end{tikzpicture}
\begin{tikzpicture}
\draw[step=1,help lines,black!20] (-0.99,-0.99) grid (8.99,8.99);
\draw[thick,->] (-1,0) -- (9,0) node[pos=0.97,below] {$x$};
\draw[thick,->] (0,-1) -- (0,9) node[pos=0.97,left] {$y$};
% Graph 2
\draw[very thick,color=black,domain=-1:9] plot (\x,{0.5*\x});
\end{tikzpicture}
\end{document}
MWE (with \savebox)
\documentclass[tikz]{standalone}
\begin{document}
\newsavebox{\mygrid}
\savebox{\mygrid}{
\draw[step=1,help lines,black!20] (-0.99,-0.99) grid (8.99,8.99);
\draw[thick,->] (-1,0) -- (9,0) node[pos=0.97,below] {$x$};
\draw[thick,->] (0,-1) -- (0,9) node[pos=0.97,left] {$y$};
}
\begin{tikzpicture}
\usebox{\mygrid}
% Graph 1
\draw[very thick,color=black,domain=-1:9] plot (\x,{\x});
\end{tikzpicture}
\begin{tikzpicture}
\usebox{\mygrid}
% Graph 2
\draw[very thick,color=black,domain=-1:9] plot (\x,{0.5*\x});
\end{tikzpicture}
\end{document}
Screenshots
Graph 1
Graph 2



\saveboxdoesn't work in my case? – Andreas Schneider Dec 19 '19 at 16:23\saveboxsaves a box. A completetikzpictureis a box, a collection of paths is not a box. But thanks for completing your MWE! (+1) – Dec 19 '19 at 16:25\picdifferent than using a macro? I suppose I should read the manual... – Hood Chatham Dec 19 '19 at 16:29\path (0,0) -- (3,0) pic[midway,sloped] {<some pic>};which clearly does not work with\newcommand. – Dec 19 '19 at 16:33\savebox. It does work, but is not as versatile as the pic (but a bit faster to compile). – Dec 19 '19 at 16:36