# Keep path within axis

In the following example:

\documentclass{article}
\usepackage{tikz, pgfplots}
\usepgfplotslibrary{fillbetween}
\pgfplotsset{compat=1.14}
\begin{document}
\begin{tikzpicture}
\begin{axis}
\addplot [name path = plot1] coordinates {
(0, 2)
(2, 5)
(3, 7)
};
\draw [name path = plot2] (0, 2) -- (5, 2);
\end{axis}
\end{tikzpicture}
\end{document}


the path plot2 extends out of the axis scope as seen in the result:

How to make the axis adjust itself to enclose the path plot2 as much as it does the adjustment to enclose the path plot1?

• Your definition of "within" is a bit strange, that line is cut off, so it never (visibly) goes outside the axis. Are you after something like \draw [name path = plot2] (0, 2) -- (\pgfkeysvalueof{/pgfplots/xmax}-0.5, 2);? Or \draw [name path = plot2] (0, 2) -- (end |- 5, 2);, after adding coordinate (end) at the end of the first \addplot? – Torbjørn T. Dec 6 '17 at 21:33
• @TorbjørnT. I want axis to adjust itself to enclose completely the path plot2 as much as it does the adjustment to enclose the path plot1. – Viesturs Dec 6 '17 at 21:36
• Any reason why you can't use \addplot for that line as well? – Torbjørn T. Dec 6 '17 at 21:40
• @TorbjørnT. In the end I would be using \path as the path plot2 does not need to be drawn. Can I use \addplot to construct a path and not draw the actual line? – Viesturs Dec 6 '17 at 21:41
• \addplot [draw=none,name path = plot2] coordinates {(0, 2)(5, 2)}; – Torbjørn T. Dec 6 '17 at 21:43

pgpflots doesn't take \paths into account when calculating the bounding box, but you can draw the line with \addplot instead. If the line should not be visible, add draw=none to the \addplot settings.

\documentclass{article}
\usepackage{pgfplots}
\usepgfplotslibrary{fillbetween}
\pgfplotsset{compat=1.14}
\begin{document}
\begin{tikzpicture}
\begin{axis}
\addplot [name path = plot1] coordinates {
(0, 2)
(2, 5)
(3, 7)
} coordinate (end);
\addplot [draw=none,name path = plot2] coordinates {(0, 2)(5, 2)};

\addplot [blue!10] fill between[of=plot1 and plot2];
\end{axis}
\end{tikzpicture}
\end{document}