# Tikz: how to change the order of overlapping objects?

I want to draw some overlapping rectangles, for example:

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{shapes,backgrounds}
\begin{document}

\begin{tikzpicture}
\draw [fill=blue,ultra thick] (0.4,0.5) rectangle (0,1);
\draw [fill=red,ultra thick] (0,0.3) rectangle (1,1);
\draw [fill=green,ultra thick] (0,0) rectangle (0.5,0.5);
\end{tikzpicture}

\end{document}


But I want (in this example) the green rectangle under the red and the red under the blue. Is that possible (without changing the order of commands)?

More explanation: the latex commands are generated by a C++ program which computes coordinates of some rectangles. I want to draw them and they can overlap. The program computes the rectangles in some order and I want to show them in the reverse order. (It seems difficult to me to write the lines of C++ output to a file in reverse order.)

Here is what I have and what I want:

• Please add a MWE so that we can reproduce your example. Adding screenshots of the problem (in addition to the MWE) and screenshots of your desired results would be nice too. – Alenanno Apr 12 '15 at 10:18
• I added the MWE for you, but I am not sure what you want to achieve yet. :) – Alenanno Apr 12 '15 at 10:24
• Is this better? – Helena Apr 12 '15 at 10:27
• Draw green first, red second and blue last. – remus Apr 12 '15 at 11:11
• Better explanation: the latex commands are generated by a C++ program which computes coordinates of some rectangles. I want to draw them and they can overlap. The program computes the rectangles in some order and I want to show them in the reverse order. (It seems difficult to me to write the lines of C++ output to a file in reverse order.) – Helena Apr 12 '15 at 11:26

A simple sequence of \draw commands can also be reverted by TeX. In the following example, macro \reversedraws goes before the sequence of \draw commands, which should be reverted. It stores them in macro \collect@draws in reverse order. After the last \draw, the now reverted list is output:

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{shapes,backgrounds}

\usepackage{etoolbox}% provides \preto
\makeatletter
\newcommand*{\collect@draws}{}
\newcommand*{\reversedraws}{%
\renewcommand*{\collect@draws}{}% initialize
\look@for@draw
}
\newcommand*{\look@for@draw}{%
\@ifnextchar\draw{%
\catch@draw
}{%
\collect@draws % output the result
}%
}
\def\catch@draw\draw#1;{%
\preto\collect@draws{\draw#1;}%
\look@for@draw
}
\makeatother

\begin{document}
\begin{tikzpicture}
\reversedraws
\draw [fill=blue,ultra thick] (0.4,0.5) rectangle (0,1);
\draw [fill=red,ultra thick] (0,0.3) rectangle (1,1);
\draw [fill=green,ultra thick] (0,0) rectangle (0.5,0.5);
\end{tikzpicture}
\end{document}


Of course fixing the C++ tool program to output the correct order is the better approach and can be done more efficient in linear time there. In the example above, the run time behavior is quadratic.