TikZ,避免不必要的临时坐标计算

TikZ,避免不必要的临时坐标计算

我想知道是否有更简单的方法来获得类似的图形:(1)避免手动调整每个彩色框的大小,(2)避免手动计算绘制箭头的每个框的中间。

\documentclass{book}
\usepackage{tikz}
\usetikzlibrary{calc}

\def\constraint#1{\textsc{#1}}

\begin{document}

\begin{tikzpicture}
\node (ctr) {$\constraint{increasing\_max\_peak}$};
\fill[brown!20]  ($(ctr.south west)+(0.1,0)$)  rectangle ($(ctr.north west)+(2.07,0)$);
\fill[pink!20]   ($(ctr.south west)+(2.07,0)$) rectangle ($(ctr.north west)+(2.9,0)$);
\fill[violet!20] ($(ctr.south west)+(2.9,0)$)  rectangle ($(ctr.north east)-(0.1,0)$);
\node (ctr1) {$\constraint{increasing\_max\_peak}$};
\draw[->] ($(ctr.south west)+(1.085,0)$) -- ($(ctr.south west)+(1.085,-0.7)$) node[below] {\scriptsize \constraint{Condition}};
\draw[->] ($(ctr.south west)+(2.485,0)$) -- ($(ctr.south west)+(2.485,-0.3)$) node[below] {\scriptsize \constraint{Feature}};
\draw[->] ($(ctr.south west)+(3.35,0)$) -- ($(ctr.south west)+(3.35,-0.7)$) node[below] {\scriptsize \constraint{Pattern}};
\end{tikzpicture}

\end{document}

在此处输入图片描述

答案1

例如,您可以使用 库\subnode中的 s 。请注意,这需要在环境中tikzmark添加选项。这样您就可以使用子节点的锚点来绘制框和箭头。remember picturetikzpicture

您还可以利用该backgrounds库来避免两次绘制相同的节点。

在此处输入图片描述

\documentclass[border=5mm]{standalone}
\usepackage{tikz}
\usetikzlibrary{
  tikzmark,
  backgrounds
}

\newcommand\constraint[1]{\textsc{#1}}

\begin{document}

\begin{tikzpicture}[remember picture]
\node (ctr) {$\constraint{\subnode{i}{increasing}\subnode{a}{\_}\subnode{m}{max}\subnode{b}{\_}\subnode{p}{peak}}$};
\begin{scope}[on background layer]
  \fill[brown!20] (i.north west) rectangle (a.south);
  \fill[pink!20] (a.south) rectangle (m.north east);
  \fill[violet!20] (b.north |- p.north) rectangle (p.south  east);
\end{scope}

\begin{scope}[
  every node/.append style={font=\scriptsize}
]
  \draw [->] (i.south) -- ++(0,-0.7) node[below] {\constraint{condition}};
  \draw [->] (m.south) -- ++(0,-0.4) node[below] {\constraint{feature}};
  \draw [->] (p.south) -- ++(0,-0.7) node[below] {\constraint{pattern}};
\end{scope}

\end{tikzpicture}

\end{document}

相关内容