Coordinates on the x axis of tikz plot are incorrectly displayed

axisgridspgfplotstikz-pgf

I am trying to draw a function as well as a shaded grid on the same axes. Although I use a step size of 1cm in the grid between -3 and 0, the xticks, as well as the shaded region look misplaced. how can I solve this? thanks

\begin{tikzpicture}
\begin{axis}[axis lines=right,  
    axis x line=middle,
    xlabel={$t$},
    ylabel={$x$},
    %position spatial axes label on top of the axis
    every axis y label/.style={
    at={(ticklabel* cs:1.05)},
    anchor=south,
},  xtick={-7, -6, -5,  -4,  -3, -2 ,-1},
%    xticklabels={$-7$, $-6$, $-5$,  $-4$,  $-3$, $-2$ ,$-1$},
%    ytick={0.2,0.4,0.6,0.8,1},
    domain=-7:0,
    xmin=-7, xmax=0,
    ymin=0, ymax=1.1,
    samples=500,
]
    \addplot+[mark=none,color=black] {e^(x/2.75)};
\draw[step=1cm,color=gray!50,opacity=0.5] (-3,0) grid (0,1);
\filldraw [fill=gray, draw=black,opacity=0.5]
-- (-3,0)
-- (-3,0.2)
-- (-2,0.2)
-- (-2,0.4)
-- (-1,0.4)
-- (-1,0.6)
-- (0,0.6)
-- (0,0)
-- cycle;
\end{axis}
\end{tikzpicture}

enter image description here

Best Answer

The coordinates inside an axis environment are not the same as those outside it. The way it works is that pgpflots sets the size of the axis, and then scales things so that the range (defined either by the data or xmin/xmax) fits inside that width.

If you set

scale only axis,
width=7cm, height=5.5cm

things might look better.

scale only axis is required because pgfplots leaves 45pt of space in both x- and y-directions for axis labels. Hence, if you set width=345pt, the width of the axis box alone will be 300pt. width=7cm is because your x-range is from -7 to 0, and you have a tick every 1 axis unit. height=5.5cm is because your y-range is from 0 to 1.1 with ticks every 0.2 axis units.

\documentclass{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.18}
\begin{document}
\begin{tikzpicture}
\begin{axis}[axis lines=right,  
    axis x line=middle,
    xlabel={$t$},
    ylabel={$x$},
    %position spatial axes label on top of the axis
    every axis y label/.style={
       at={(ticklabel* cs:1.05)},
       anchor=south,
    },
    xtick={-7, ..., -1},
    ytick={0,0.2,...,1.1},
    domain=-7:0,
    xmin=-7, xmax=0,
    ymin=0, ymax=1.1,
    samples=50,
    scale only axis,
    width=7cm, height=5.5cm
]
\addplot+[mark=none,color=black] {e^(x/2.75)};

\draw[step=1cm,color=gray!50,opacity=0.5] (-3,0) grid (0,1);
\filldraw [fill=gray, draw=black,opacity=0.5]
(-3,0) -| (0,0.6) -| (-1,0.4) -| (-2,0.2) -| cycle;

\end{axis}
\end{tikzpicture}
\end{document}

enter image description here