[Tex/LaTex] Relative node positioning with calc library

calculationspositioningtikz-pgf

Hi I'm trying to place same nodes relative to each other. I'm trying to place a node in the middle between two other nodes, but also half a cm to the right.

\usepackage{tikz}
\usetikzlibrary{calc}

\begin{tikzpicture}
\node (p4) {$\hat{4}$} ;
\node[below=1cm of p4] (p3) {$3$} ;
\node[right=3cm of p4] (p1) {$\hat{1}$} ;
\node[below=1cm of p1] (p2) {$2$} ;
\node[below right={1/sqrt(2)}cm of p4] (v1) {$v_1$} ;
\end{tikzpicture}

I don't get why this isn't working… I get the following error

Package PGF Math Error: Unknown operator c' orcm' (in
'{1/sqrt(2)}cm ').

Best Answer

You must:

  • Add the positioning library.
  • Use \pgfmathparse to calculate the 1/sqrt(2) expresion.
  • Use \pgfmathresult where is the result of calculation.

    \documentclass{article}
    \usepackage{tikz}
    \usetikzlibrary{calc,positioning}
    \begin{document}
    \begin{tikzpicture}
    \node (p4) {$\hat{4}$} ;
    \node[below=1cm of p4] (p3) {$3$} ;
    \node[right=3cm of p4] (p1) {$\hat{1}$} ;
    \node[below=1cm of p1] (p2) {$2$} ;
    \pgfmathparse{1/sqrt(2)}
    \node[below right=\pgfmathresult cm of p4] (v1) {$v_1$} ;
    \end{tikzpicture}
    \end{document}
    

Or if you don't use some unit like cm, you don't need \pgfmathparse.

Edit

To avoid problems with \pgfmathparse{} and \pgfmathresult you can use your own macro with \pgfmathsetmacro{...}. This change avoids the problem showed by @percusse.

\begin{tikzpicture}
\node (p4) {$\hat{4}$} ;
\node[below=1cm of p4] (p3) {$3$} ;
\node[right=3cm of p4] (p1) {$\hat{1}$} ;
\node[below=1cm of p1] (p2) {$2$} ;
\pgfmathsetmacro{\myroot}{1/sqrt(2)} % <- 
\node[line width=3mm,below right=\myroot cm of p4] (v1) {$v_1$} ;
\end{tikzpicture}

Although this is not relevant to this specific problem, it may be useful for other cases.

Related Question