Is it possible to reuse a part of a tikz image
To fill in @philosodad's first way, this does what you want and obeys DRY:
\begin{scope}[yscale=2.0,yshift=-3,xscale=0.1]
\foreach \i/\mu/\xmin/\xmax in {1/5/0/10,2/10/5/15} {
\draw[domain=\xmin:\xmax] plot[id=gauss\i] function{exp(-(x-\mu)*(x-\mu)/2/2/2.0)/sqrt(pi)/2};
}
\end{scope}
The scope environment isn't required (you can put those options on the \draw
line) but it does make the line shorter. :-)
If you want to put that in multiple places, just assign it to a box.
\usetikzlibrary{matrix}
\newsavebox{\gaussians}
\savebox{\gaussians}{
\begin{tikzpicture}
\begin{scope}[yscale=2.0,yshift=-3,xscale=0.1]
\foreach \i/\mu/\xmin/\xmax in {1/5/0/10,2/10/5/15} {
\draw[domain=\xmin:\xmax] plot[id=gauss\i] function{exp(-(x-\mu)*(x-\mu)/2/2/2.0)/sqrt(pi)/2};
}
\end{scope}
\end{tikzpicture}
}
\begin{tikzpicture}
\node[matrix of nodes] {
\usebox{\gaussians} & foo & \usebox{\gaussians} \\
bar & \usebox{\gaussians} & baz \\
};
\end{tikzpicture}
Edit: Following Yossi's suggestion, I rewrote this to use a saved box rather than a macro.
With TiKZ 3.0 pics
it's easy to reuse part of your image. You need to declare the reusable part inside a pic
and place where you want, even inside a matrix
.
\documentclass[border=2mm,tikz]{standalone}
\tikzset{
mygauss/.pic={
\draw[yscale=2.0,yshift=-3,xscale=0.1,domain=0:10] plot[id=gauss1]
function{exp(-(x-5)*(x-5)/2/2/2.0)/sqrt(pi)/2};
\draw[yscale=2.0,yshift=-3,xscale=0.1,domain=5:15] plot[id=gauss2]
function{exp(-(x-10)*(x-10)/2/2/2.0)/sqrt(pi)/2};
}}
\begin{document}
\begin{tikzpicture}
\matrix (A) [column sep=5mm, row sep=3mm] {
\pic{mygauss}; & \pic{mygauss}; & \pic{mygauss}; \\
\pic[red]{mygauss}; & \pic{mygauss}; & \pic{mygauss}; \\
\pic{mygauss}; & \pic{mygauss}; & \pic[green,dashed]{mygauss}; \\};
\end{tikzpicture}
\end{document}
As usual with gnuplot we neeed to compile with -shell-escape as in pdflatex -shell-escape myfile.tex
People seem to be answering a different question...I may be wrong but I think you are looking for \savebox
? Would this not save latex from re-rendering the TikZ code every time? I don't know how many times you need to put those plots in your document, but if you are going to define a macro to do it, you may consider putting the whole thing in a \savebox
:
\newsavebox{\myneatfigurethatineedalot}
\savebox{\myneatfigurethatineedalot}{
A bunch of latex code, tikz and
what-not that you need to place on every corner of every page
}
\usebox{\myneatfigurethatineedalot} %use this wherever you want it!
I think that \savebox
is better than a macro in this case, because a) what is in the box is self-contained (the typesetting of the content of the box does not depend on the location in the text) and b) it is relatively expensive to render and by using a \savebox
you are telling the texengine to simply reuse the result of the rendering, while the macro would tell it to re-render everything from scratch.