[Tex/LaTex] pfgplots height and width not working correctly

dimensionsgraphicspgfplots

I'm trying to insert an image with added axes using pgfplots, which has the same aspect ratio as the original image, i.e. if the x axis is half the size of the width of the image, then the y axis needs to also be half the size of the height of the image (as opposed to the pgfplots default, which seems to distort everything into an approximate square shape).

The simplest way to achieve this seems to be to just calculate what the width and height values should be, then manually define them in the code. The problem is this isn't working. The resulting plot isn't quite the same dimensions as what I specified (height seems a little smaller than it should be) and the image is noticeably distorted. What is going on, and how can I fix this?

Below is the code I've been using:

\documentclass{article}
\usepackage{pgfplots}
\begin{document}
    \begin{tikzpicture}
    \begin{axis}[
    xlabel={x axis},ylabel={y axis},
    xtick distance=1,ytick distance=1,
    width=10cm,height=4.44062cm,
    enlargelimits=false]
    \addplot graphics[xmin=0, xmax=5, ymin=0, ymax=5] {Images/test};
    \end{axis}
\end{tikzpicture}
\end{document}

Test image used in above code: (581px wide, 258px high)
test image

Bonus: is there a way to get images in plots to automatically retain their aspect ratio when resized? I had a recent question on this topic that didn't get any responses. This would be ideal, but manually scaling it as above is ok too.

Best Answer

Thanks to @TorbjørnT. for pointing out the issue. This is just a more detailed summary of their solution.

This issue comes about due to a misunderstanding of the meaning of width and height. These refer to the dimensions of the bounding box of the final figure, i.e. the area containing the plot, axes, titles, a small amount of surrounding white space, etc. It was incorrectly assumed these referred to the dimensions of the axes, however they can be redefined to have this meaning by including the line scale only axis=true in the axis environment. Thus the final code will be as follows:

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