# Tikz overlaying picture with \newcommand


\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage[left=2cm, right=5cm, top=2cm]{geometry}
\usepackage{tikz}
\usetikzlibrary{positioning,fit}
\newcommand{\tklines}[1]
{
\begin{tikzpicture}[red,overlay]
\draw (0,#1)--++(5,0);
\end{tikzpicture}%
}
\begin{document}
\begin{tikzpicture}[overlay]
\draw (0,0)--++(5,0);
\end{tikzpicture}%
\begin{tikzpicture}[overlay]
\draw (0,1)--++(5,0);
\end{tikzpicture}%
\begin{tikzpicture}[overlay]
\draw (0,2)--++(5,0);
\end{tikzpicture}
\hspace{5cm}
\tklines{0}
\tklines{1}
\tklines{2}
\end{document}


The result is displayed in following picture. See red lines going to right side. I have tried to search several time but I think i am missing something. Kindly help.

• you have {  so put a space before each tikzpicture, use {% Apr 7 '20 at 19:00
• I have put a the percentage sign just after the curly brackets i.e. the curly brackets of the \newcommand third argument, but it does not solve the problem - lines are still going to the right side. Apr 8 '20 at 5:50

As David Carlisle said, only a few % are missing, one in the command definition, before the \begin{tikzpicture}, and one after each call of \tklines{X}.

\documentclass{article}

\usepackage[utf8]{inputenc}
\usepackage[left=2cm, right=5cm, top=2cm]{geometry}
\usepackage{tikz}

\usetikzlibrary{positioning,fit}

\newcommand{\tklines}[1]{% <-[ HERE ]
\begin{tikzpicture}[red,overlay]
\draw (0,#1)--++(5,0);
\end{tikzpicture}%
}

\begin{document}

\begin{tikzpicture}[overlay]
\draw (0,0)--++(5,0);
\end{tikzpicture}%
\begin{tikzpicture}[overlay]
\draw (0,1)--++(5,0);
\end{tikzpicture}%
\begin{tikzpicture}[overlay]
\draw (0,2)--++(5,0);
\end{tikzpicture}
%
\hspace{5cm}
%
\tklines{0}% <-[ HERE ]
\tklines{1}% <-[ HERE ]
\tklines{2}

\end{document}

• Thank you. I was thinking that when i have already put '% in the new command why should it be put <-[Here]. It is working. Apr 11 '20 at 5:42