[Tex/LaTex] pgfplots: retain aspect ratio of image

dimensionsgraphicspgfplots

I'm trying to insert an image with an axis, which can be achieved with the below code and the pgfplots package. How do I adjust this such that the axes have the same aspect ratio as the original image? Is there a setting that will read in the aspect ratio automatically and use this, or perhaps a way to automatically calculate the height from the image dimensions and defined axis width?

\begin{tikzpicture}
\begin{axis}[
xlabel={x axis},ylabel={y axis},
xtick distance=1,ytick distance=1,
width=14cm,
enlargelimits=false,
scale only axis=true,
]
\addplot graphics[xmin=0, xmax=5, ymin=0, ymax=5] {Images/test};
\end{axis}
\end{tikzpicture}

Best Answer

Here's a slightly adapted version of Christian Feuersänger's answer to \addplot graphics: maintaining image's aspect ratio despite different scaling of axes (the only difference being that this version makes sure that the smaller of the unit vectors is 1):

\documentclass{article}

\usepackage{pgfplots}
\pgfplotsset{compat=newest}
\begin{document}

\makeatletter
\newcommand\addplotgraphicsnatural[2][]{%
    \begingroup
    % set options in this local group (will be lost afterwards):
    \pgfqkeys{/pgfplots/plot graphics}{#1}%
    % measure the natural size of the graphics:
    \setbox0=\hbox{\includegraphics{#2}}%
    %
    % compute the required unit vector ratio:
    \pgfmathsetmacro{\xfactor}{\wd0/(\pgfkeysvalueof{/pgfplots/plot graphics/xmax} - \pgfkeysvalueof{/pgfplots/plot graphics/xmin})}%
    \pgfmathsetmacro{\yfactor}{\ht0/(\pgfkeysvalueof{/pgfplots/plot graphics/ymax} - \pgfkeysvalueof{/pgfplots/plot graphics/ymin})}\yfactor%
    % The smaller of the unit vectors should be 1, so the other needs to be scaled appropriately
    \pgfmathsetmacro{\xunit}{\xfactor<\yfactor ? 1 : \xfactor/\yfactor}
    \pgfmathsetmacro{\yunit}{\xfactor<\yfactor ? \yfactor/\xfactor : 1}
    %
    % configure pgfplots to use it.
    % The \xdef expands all macros except those prefixed by '\noexpand'
    % and assigns the result to a global macro named '\marshal'.
    \xdef\marshal{%
        \noexpand\pgfplotsset{unit vector ratio*={\xunit\space \yunit}}%
    }%
    \endgroup
    %
    % use our macro here:
    \marshal
    %
    \addplot graphics[#1] {#2};
}   
\makeatother

\begin{tikzpicture}
\begin{axis}[enlargelimits=false, axis equal image]
\addplotgraphicsnatural [xmin=0, xmax=10, ymin=0, ymax=10] {snake.png};
\end{axis}
\end{tikzpicture}

\begin{tikzpicture}
\begin{axis}[enlargelimits=false, axis equal image]
\addplotgraphicsnatural [xmin=0, xmax=10, ymin=0, ymax=10] {giraffe.png};
\end{axis}
\end{tikzpicture}

\end{document}