如何在 tikz 中对齐节点标签?

如何在 tikz 中对齐节点标签?

我用代码来绘制文件系统树,并且我还使用节点标签来添加描述。

问题是如何对齐节点标签?我可以将描述添加为单独的节点并使用相对定位,但这很繁琐。

坏的:

node1    description
  node2    description
    node3    description

好的:

node1        description
  node2      description
    node3    description

梅威瑟:

\documentclass{minimal}
\usepackage{tikz}
\usetikzlibrary{trees}
\begin{document}
\tikzstyle{every node}=[draw=black,thick,anchor=west]
\tikzstyle{selected}=[draw=red,fill=red!30]
\tikzstyle{optional}=[dashed,fill=gray!50]
\begin{tikzpicture}[%
    grow via three points={one child at (0.5,-0.7) and
    two children at (0.5,-0.7) and (0.5,-1.4)},
    edge from parent path={(\tikzparentnode.south) |- (\tikzchildnode.west)}]
    \node [label={right:description}] {texmf}
        child { node [label={right:description}] {doc}}     
        child { node [label={right:description}] {fonts}}
        child { node [label={right:description}] {source}}
        child { node [selected,label={right:description}] {tex}
        child { node [label={right:description}] {generic}}
        child { node [optional,label={right:description}] {latex}}
        child { node [label={right:description}] {plain}}
    }
    child [missing,label={right:description}c] {}               
    child [missing,label={right:description}] {}                
    child [missing,label={right:description}] {}                
    child { node [label={right:description}] {texdoc}};
\end{tikzpicture}
\end{document}

答案1

您可以定义一个名为 的新节点descriptionheader,然后使用以下选项将描述节点定位在与新节点相同的水平shift={(0,0-|descriptionheader.west)}位置label

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{trees}
\begin{document}
\tikzstyle{every node}=[draw=black,thick,anchor=west]
\tikzstyle{selected}=[draw=red,fill=red!30]
\tikzstyle{optional}=[dashed,fill=gray!50]
\begin{tikzpicture}[%
    grow via three points={one child at (0.5,-0.7) and
    two children at (0.5,-0.7) and (0.5,-1.4)},
    edge from parent path={(\tikzparentnode.south) |- (\tikzchildnode.west)},
    every label/.append style={shift={(0,0-|descriptionheader.west)}}
    ]
    \node (descriptionheader) [draw=none, font=\bfseries] at (4,4ex) {Descriptions};
    \node [label={right:description}] {texmf}
        child { node [label={right:long description}] {doc}}     
        child { node [label={right:description}] {fonts}}
        child { node [label={right:description}] {source}}
        child { node [selected,label={right:description}] {tex}
        child { node [label={right:description}] {generic}}
        child { node [optional,label={right:description}] {latex}}
        child { node [label={right:description}] {plain}}
    }
    child [missing,label={right:description}c] {}               
    child [missing,label={right:description}] {}                
    child [missing,label={right:description}] {}                
    child { node [label={right:description}] {texdoc}};
\end{tikzpicture}
\end{document}

相关内容