tikz 将文本放在矩形下方

tikz 将文本放在矩形下方

我想画一个这样的人物 在此处输入图片描述

但我现在得到的是 在此处输入图片描述

有两个问题:(1) 红色和蓝色矩形的高度不同,(2) 标签stackbuffer居中对齐。我是 tikz 新手,有人可以指点一些可以改进图形的方向吗?

\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary{arrows}
\usetikzlibrary{calc}

\begin{document}

\begin{tikzpicture}[->,>=stealth',node distance=1cm]
    \draw [help lines] (0,0) grid (6,2);
    \node [text] (1) {I};
    \node [text] (2) [right of=1] {booked};
    \node [text] (3) [right of=2] {a};
    \node [text] (4) [right of=3] {ticket};
    \node [text] (5) [right of=4] {to};
    \node [text] (6) [right of=5] {China};

    \path (2) edge[bend right=70] node [above]{nsubj} (1);
    \path (2) edge[bend left=90] node [above]{dobj} (4);
    \path (4) edge[bend right=70] node [left]{det} (3);
    \path (4) edge[bend left=70] node [above]{prep} (5);
    \path (5) edge[bend left=70] node [above]{pobj} (6);

    \draw [red,thick,minimum height=2cm] (stack) ($(1.north west)$) rectangle ($(2.south east)$);
    \node [text,align=center] [below=stack] {stack};

    \draw [blue,thick,minimum height=2cm] (buffer) ($(3.north west)$) rectangle ($(6.south east)$);
    \node [text,align=center] [below=buffer] {buffer};
\end{tikzpicture}

\end{document}

答案1

你喜欢获得这样的东西吗?

在此处输入图片描述

我显著改变了你的 MWE:

  • 引入新库:chainsfitquotes
  • 删除calc,因为它没有被使用
  • 对于红色和蓝色矩形使用节点,适合txt节点
  • 定义新样式:(txttextTikZ 中使用名称,不能用于本地定义的样式)并重新定义edge样式
  • 对于边缘标签使用库quotes
  • 红色和蓝色矩形下方的文本是相应节点的标签

完成 MWE:

\documentclass[tikz,
               border=3mm]{standalone}
\usetikzlibrary{arrows, chains, fit, quotes}

\begin{document}
    \begin{tikzpicture}[
node distance = 10mm,
  start chain = A going right,
   txt/.style = {text height=2ex, text depth=0.25ex,
                 on chain},
every edge/.append style = {draw, -stealth'}
                        ]
\draw [help lines] (-1,-1) grid (10,2);
\node [txt] {I};     % nodes are in the chain
\node [txt] {booked};
\node [txt] {a};
\node [txt] {ticket};
\node [txt] {to};
\node [txt] {China};
%
\node (f1)  [draw=red, inner sep=0pt, % red rectangle
             label=below:stack, % "node below rectangle done by node label
             fit=(A-1) (A-2)] {};
\node (f2)  [draw=blue,inner sep=0pt, % blue rectangle
             label=below:buffer,% "node below rectangle done by node label
              fit=(A-3) (A-6)] {};
%
\path   (A-2) edge[bend right=70, "nsubj" '] (A-1)
        (A-2) edge[bend  left=90, "dobj"   ] (A-4)
        (A-4) edge[bend right=70, "det"   '] (A-3)
        (A-4) edge[bend  left=70, "prep"   ] (A-5)
        (A-5) edge[bend  left=70, "pobj"   ] (A-6);
    \end{tikzpicture}
\end{document}

相关内容