2

I would like to draw a pgfplots grid onto a 480x800 image. With the code below, I can see the grid has been plotted but the image doesn't show.

\documentclass{standalone}
\usepackage{tikz}
\usepackage{tikz} 
\usepackage{pgfplots} 
\pgfplotsset{compat=1.18}
\begin{document}
\def\fname{/media/sf_work/demo.png}
\begin{tikzpicture}
\begin{axis}[
        grid = both,scale=.5,
        width=480,
        height=800,
        , minor tick num=3
        , grid style={draw=gray!10,line width=.1pt}
        , major grid style={line width=0.5pt,draw=gray!50}
        , axis line style={latex-latex}
        , xticklabels = \empty
        , yticklabels = \empty
        , draw=blue!20
    ]
  \node[] (image) at (axis cs:240,400) {\includegraphics[]{\fname}};
\end{axis}
\end{tikzpicture} 
\end{document}

Output: enter image description here

bonk
  • 885
lucky1928
  • 4,151
  • You are confusing width and length (that should be lengths, so with a measurement unit) with the x and y axis ranges... – Rmano Jan 04 '24 at 18:10

1 Answers1

4

You are mixing the width and length (physical size of the picture produced) with the x and y value ranges. Notice that the figure will be vectorial, so you can't play with pixels here, not so easily at least.

\documentclass{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.18}
\begin{document}
\def\fname{/media/sf_work/demo.png}
\begin{tikzpicture}
\begin{axis}[
    grid = both, %scale removed, here it messes things up
        width=4.8cm,
        height=8cm,
        xmin=0, xmax=480, ymin=0, ymax=800,
        , minor tick num=3
        , grid style={draw=gray!10,line width=.1pt}
        , major grid style={line width=0.5pt,draw=gray!50}
        , axis line style={latex-latex}
        , xticklabels = \empty
        , yticklabels = \empty
        , draw=blue!20
    ]
    % axis cs is not needed
  \node[] (image) at (axis cs:240,400) {\includegraphics[width=2cm]{example-image-duck}};
\end{axis}
\end{tikzpicture}
\end{document}

enter image description here

Notice that pgfplots adds space for x and y labels, even if they're not there, and that normally the grid is under the picture.

Rmano
  • 40,848
  • 3
  • 64
  • 125
  • good, thanks, if image size the same as defined, I still saw a little border outside of image. image and grid lines not exactly matched. – lucky1928 Jan 04 '24 at 20:11
  • Maybe you need node[inner sep=0pt, outer sep=0pt]? (BTW: are you sure you do not look for something like https://tex.stackexchange.com/a/9562/38080?). Anyway, your best option is to post another question, using an image that everyone can use (like I did, using one of the example image available in every TeX distribution) – Rmano Jan 04 '24 at 21:05