如何相对于锚点定位元素?

如何相对于锚点定位元素?

我的代码是:

\begin{center}
    \vspace{-20pt}
    \begin{tikzpicture}[mybox/.style={rectangle, draw, minimum width=10mm, minimum height=10mm}]
    \foreach \addr/\val [count=\x] in {$0$,$1$/$28$,$6$/$\infty$,$6$/$\infty$,$6$/$25$,$0$,$6$/$\infty$} {
        \node (node\x) [mybox] at (\x,0) {\addr};
        \node[above=5mm] at (\x,0) {\footnotesize \x};
        \node[below=5mm] at (\x,0) {\val};
    }
    \node at (node1.south west-100mm,0) [below=5mm] {Edge Weight:};
    \draw[ultra thick] (node1.south west) rectangle (node7.north east);
    \end{tikzpicture}
\end{center}

我在有关使用锚点作为坐标的\node (lab) at (node1.south west-100mm,0) [below=5mm] {Edge Weight:};部分的行上收到错误。(node1.south west-100mm,0)

错误:

包 PGF 数学错误:未知函数“node1”(在“node1.south west-100mm”中)。 \node 位于(node1.south west-100mm,0)

包 PGF 数学错误:未知函数“node1”(在“node1.south west-100mm”中)。...est-100mm,0)[below=5mm] {边权重:};

我希望节点的位置lab距离 node0 的西南锚点 (-100pt,0)。我该怎么做?

我甚至尝试过写:

(node1.south west)+(-1,0)

但这也不起作用。我该如何解决这个问题?

PS 我知道写作\path (node1.south west) node at +(-35pt,-8pt) {Edge Weight:};可以解决问题,但是有没有办法直接做到这一点,而不使用路径命令而只是使用节点命令?

答案1

您可以使用xshift

\documentclass{article}
\usepackage{tikz}
\begin{document}

    \begin{tikzpicture}[mybox/.style={rectangle, draw, minimum width=10mm, minimum height=10mm}]
    \foreach \addr/\val [count=\x] in {$0$,$1$/$28$,$6$/$\infty$,$6$/$\infty$,$6$/$25$,$0$,$6$/$\infty$} {
        \node (node\x) [mybox] at (\x,0) {\addr};
        \node[above=5mm] at (\x,0) {\footnotesize \x};
        \node[below=5mm] at (\x,0) {\val};
    }
    \node at ([xshift=-10]node1.south west) [below=5mm] {Edge Weight:};
    \draw[ultra thick] (node1.south west) rectangle (node7.north east);
    \end{tikzpicture}

\end{document}

通过这个小的调整,你的代码将产生:

在此处输入图片描述

为了使代码更容易阅读,我将 for 循环替换为

    \foreach \addr/\val [count=\x] in {0,1/28,6/\infty,6/\infty,6/25,0,6/\infty} {
        \node (node\x) [mybox] at (\x,0) {$\addr$};
        \node[above=5mm] at (\x,0) {\footnotesize \x};
        \node[below=5mm] at (\x,0) {$\val$};
    }

答案2

如果您想使用该calc库,您需要将节点操作写如下:

 \node at ($(node1.south west)+(-1,0)$) 

你将拥有:

结果

完整代码:

\documentclass[border=10pt]{standalone}
\usepackage{tikz}
\usetikzlibrary{calc}
\begin{document}
\begin{tikzpicture}[mybox/.style={rectangle, draw, minimum width=10mm, minimum height=10mm}]
    \foreach \addr/\val [count=\x] in {$0$,$1$/$28$,$6$/$\infty$,$6$/$\infty$,$6$/$25$,$0$,$6$/$\infty$} {
        \node (node\x) [mybox] at (\x,0) {\addr};
        \node[above=5mm] at (\x,0) {\footnotesize \x};
        \node[below=5mm] at (\x,0) {\val};
    }
    \node at ($(node1.south west)+(-1,0)$) [below=5mm] {Edge Weight:};
    \draw[ultra thick] (node1.south west) rectangle (node7.north east);
\end{tikzpicture}
\end{document}

相关内容