[Tex/LaTex] Arrange / align external images in grid with TikZ

graphicstikz-pgf

I'm trying to use TikZ to combine four raster images into a single figure and annotate the images. If you feel like asking why, see *.

My first problem is arranging / aligning the images in a grid.

The code below sort of gets the job done, but the order in which the images appear is not what I would expect. I would expect

[a][b]
[c][d]

but I get
Screenshot of images a, b, c, d arranged in grid

% remember usepackage{tikz}
\begin{figure}
\begin{tikzpicture}
    \node[anchor=north west ,inner sep=0] (frame1) at (0,0)        
    {\includegraphics[width=0.45\textwidth]{a.png}};

    \node[anchor=north east,inner sep=0] (frame2) at (0,0)        
    {\includegraphics[width=0.45\textwidth]{b.png}};

    \node[anchor=south west,inner sep=0] (frame3) at (0,0)        
    {\includegraphics[width=0.45\textwidth]{c.png}};

    \node[anchor=south east,inner sep=0] (frame4) at (0,0)        
    {\includegraphics[width=0.45\textwidth]{d.png}};
\end{tikzpicture}
\caption{My caption}
\end{figure}

How would you arrange these four images in a 2×2 grid, preferably in a predictable order?

*Scientific journals often expect a single pdf or tiff file for each figure, combining images with the subfigure environment or similar is not an option since they do not support exporting the figure you created to a seperate pdf file, but TikZ does. And I need this single pdf file to submit as the final figure. Combining and annotating in an external graphics editor like Inkscape introduces the problem of fonts, font sizes etc. Much nicer to have LaTeX do the annotation to get the right font and size.

Best Answer

Try:

\documentclass{article}
\usepackage{graphicx}
\usepackage{tikz}
\usetikzlibrary{positioning}

\begin{document}
\begin{figure}[htb]
    \centering
    \begin{tikzpicture}[
 image/.style = {text width=0.45\textwidth, 
                 inner sep=0pt, outer sep=0pt},
node distance = 1mm and 1mm
                        ] 
\node [image] (frame1)
    {\includegraphics[width=\linewidth]{example-image-a}};
\node [image,right=of frame1] (frame2) 
    {\includegraphics[width=\linewidth]{example-image-b}};
\node[image,below=of frame1] (frame3)
    {\includegraphics[width=\linewidth]{example-image-c}};
\node[image,right=of frame3] (frame4)
    {\includegraphics[width=\linewidth]{example-image}};
\end{tikzpicture}
    \caption{My caption}
\end{figure}
\end{document}

enter image description here

As you can see, I add TikZ library `positioning, by which I control distance between picture. Also I use it in placement of nodes with images.