TikZ:多线节点的定位

TikZ:多线节点的定位

您是否知道一种根据第一行对齐多行节点的优雅方法,例如用于图例?

比较一下这个例子:

\documentclass{article}
\usepackage[%
  paperwidth=7.5cm,%
  paperheight=5.5cm,%
  margin=0.25cm,%
  marginparwidth=0cm,%
  centering,%
]{geometry}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{xcolor}
\usepackage{tikz}
\usetikzlibrary{positioning}
\pagestyle{empty}
%%%%%%%%%%%%%%%%
\begin{document}
\sffamily
%--------------------------------------%
\newlength{\tikztwo}
\settowidth{\tikztwo}{\,two (2) lines\,}
\newlength{\tikzthree}
\settowidth{\tikzthree}{\ three (3)\,}
%--------------------------------------%
\begin{tikzpicture}[very thick,every node/.style={node distance=0.2cm}]
  % The grid:
  \draw[step=0.1cm,very thin, lightgray] (0,0) grid (6,4.5);
  \draw[step=0.5cm,thin, gray] (0,0) grid (6,4.5);
  %------------------------------------------------%
  % Only for comparison:
    \draw[blue,text=black] (0.25,3.5) -- (1,3.5)
      node[anchor=west]{one line entry};
  %------------------------------------------------%
    % No positioning at all, "anchor=north west" is even worse:
    \draw[magenta,text=black] (3.25,3.5) -- (4,3.5)
      node[anchor=west,text width=\tikztwo]{two lines entry 0};
  %------------------------------------------------%
    % First attempt, node (A) only for positioning:
    \draw[green] (0.25,2.5) -- (1,2.5) node[anchor=west](A){two};
    \draw (2.12,2.285) node[text width=\tikztwo]{two (2) lines entry 1};
    % Second attempt, node (posA) only for positioning:
    \draw[green] (3.25,2.5) -- (4,2.5) node[anchor=west](nodeA){} node[anchor=west](posA){two}
      node[below right=-0.439cm and -0.276cm of nodeA,text=black,text width=\tikztwo]
      {two (2) lines entry 2};
  %------------------------------------------------%
    % First attempt, node (B) only for positioning:
    \draw[red] (0.25,1.5) -- (1,1.5) node[anchor=west](B){three};
    \draw (1.88,1.048) node[text width=\tikzthree] {three (3) lines entry 1};
    % Second attempt, node (posB) only for positioning:
    \draw[red] (3.25,1.5) -- (4,1.5) node[anchor=west](nodeB){} node[anchor=west](posB){three}
      node[below right=-0.411cm and -0.276cm of nodeB,text=black,text width=\tikzthree]
      {three (3) lines entry 2};
\end{tikzpicture}
\end{document}

首先,您可以看到一个没有定位的两行节点。之后,我展示了两种管理我想要的内容的尝试。不过,这两种方法都有缺点:这两种方法的定位都是手动完成的。
对于第一种方法,如果您更改路径的坐标,则必须更改节点的坐标。
对于第二种方法,这种情况不会发生,但是如果您更改文本,则必须更改坐标,确切地说,如果添加或删除了大写字母长度的符号(删除带括号的数字以进行测试)。另外,我必须更改第二协调发挥作用x 轴反之亦然。

顺便说一句:我标记“仅用于定位”的节点可以在工作完成后删除或注释掉。

答案1

如果您使用锚点mid west来对齐节点,这将引用mid第一行的高度,从而给出您想要的结果:

\documentclass{standalone}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
    \draw [blue, text=black] (0.25,3.5) -- ++(0.75,0) node (A) [anchor=mid west]{one line entry};
    \draw [magenta, text=black] (A.east) -- ++(0.75,0) node (B) [anchor=mid west, text width=1.5cm]{two lines entry 0};
\end{tikzpicture}
\end{document}

相关内容