# Cropping a plot with an image

I have a plot with an image, which is created with the below code, and renders as the top plot in the image below. If I decide part of the plot contains unnecessary data, how do I crop this out such that it renders like the second plot below? Also, it's important that the aspect ratio of the image is not distorted.

\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,
tick align=outside,]
\addplot graphics[xmin=0, xmax=5, ymin=0, ymax=5] {Images/test};
\end{axis}
\end{tikzpicture}
\end{document}


test image used in above code

You can clip the image, but imho you will have to calculate the changes in the height key manually. Also it would be better to preserve the ratio of the image (it makes the calculation easier):

\documentclass{article}
\usepackage{pgfplots}
\begin{document}
\newsavebox\mygraphic
\savebox\mygraphic{\includegraphics{plot}}

\begin{tikzpicture}
\begin{axis}[
xlabel={x axis},ylabel={y axis},
xtick distance=1,ytick distance=1,
width=0.5\wd\mygraphic,height=0.5\ht\mygraphic,
enlargelimits=false,
scale only axis=true,
tick align=outside,]
\addplot graphics[xmin=0, xmax=5, ymin=0, ymax=5,includegraphics={keepaspectratio}] {plot};
\end{axis}
\end{tikzpicture}

\begin{tikzpicture}
\begin{axis}[
xlabel={x axis},ylabel={y axis},
xtick distance=1,ytick distance=1,
width=0.5\wd\mygraphic,height=0.8333\ht\mygraphic, %height= 5/3*0.5
enlargelimits=false,
scale only axis=true,
tick align=outside,]
\addplot graphics[xmin=1, xmax=4, ymin=0, ymax=5, includegraphics={trim=0.2\wd\mygraphic{} 0pt  0.2\wd\mygraphic{} 0pt,clip,keepaspectratio}] {plot};
\end{axis}
\end{tikzpicture}

\end{document}


Something like

\addplot graphics[xmin=0.8, xmax=3.8, ymin=0.95, ymax=5,
includegraphics={trim=50 72 110 0,clip,keepaspectratio}] {Images/test};


The trim coordinates give the amounts to trim off the picture on the four sides, in Postscript points. So you will have to measure your image first. And then you will have to fiddle a bit to get it right. I think it is easier to just crop the image in an image editor. With the keepaspectratio the aspect ratio is not changed. If your trimming is not consistent with the aspect ratio that will show as a white space at the top or the right. Then you can adjust it.