![如何正确连接表格中的节点](https://linux22.com/image/350490/%E5%A6%82%E4%BD%95%E6%AD%A3%E7%A1%AE%E8%BF%9E%E6%8E%A5%E8%A1%A8%E6%A0%BC%E4%B8%AD%E7%9A%84%E8%8A%82%E7%82%B9.png)
我希望表中创建的节点通过一条线连接起来。理想情况下,这些线从左侧节点的边框右中边缘连接,从右侧节点的边框左中边缘连接。我在代码末尾列出了节点连接列表。您可以看到,它显然没有正确映射到表中。
\documentclass{article}
\usepackage{booktabs}
\usepackage{tikz}
\usepackage{array}
\newcommand\mybox[2]{\tikz[remember picture]{\node (#2) [draw=black, inner sep=4pt, anchor=text, rounded corners=1mm] {#1};}}
\setlength{\tabcolsep}{0.5in}
\setlength{\extrarowheight}{0.3in}
\begin{document}
\begin{tabular}{rl}
\mybox{Molecular}{molecular} & \mybox{Diamond}{diamond} \\
\mybox{Amorphous}{amorph} & \mybox{Sodium}{na} \\
\mybox{Metallic}{metal} & \mybox{Carbon Dioxide}{carbondiox} \\
\mybox{Covalent Network}{covnet} & \mybox{Glass}{glass}
\end{tabular}
\begin{tikzpicture}
\draw (molecular) -- (carbondiox);
\draw (amorph) -- (glass);
\draw (metal) -- (na);
\draw (covnet) -- (diamond);
\end{tikzpicture}
\end{document}
答案1
您需要remember picture
和环境overlay
的键tikzpicture
,以控制线路连接的位置,只需更改为(molecular)
或节点的任何(molecular.east )
锚点west
,,,,,...north
south
north east
north west
\documentclass{article}
\usepackage{booktabs}
\usepackage{tikz}
\usepackage{array}
\newcommand\mybox[2]{\tikz[remember picture]{\node (#2) [draw=black, inner sep=4pt, anchor=text, rounded corners=1mm] {#1};}}
\setlength{\tabcolsep}{0.5in}
\setlength{\extrarowheight}{0.3in}
\begin{document}
\begin{tabular}{rl}
\mybox{Molecular}{molecular} & \mybox{Diamond}{diamond} \\
\mybox{Amorphous}{amorph} & \mybox{Sodium}{na} \\
\mybox{Metallic}{metal} & \mybox{Carbon Dioxide}{carbondiox} \\
\mybox{Covalent Network}{covnet} & \mybox{Glass}{glass}
\end{tabular}
\begin{tikzpicture}[remember picture,overlay]
\draw (molecular.east) -- (carbondiox.west);
\draw (amorph.east) -- (glass.west);
\draw (metal.east) -- (na.west);
\draw (covnet.east) -- (diamond.west);
\end{tikzpicture}
\end{document}
答案2
使用没有覆盖的纯 TikZ 也是可行的。
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{matrix}
\begin{document}
\begin{tikzpicture}[
column 1/.style={anchor=east},
column 2/.style={anchor=west},
]
\matrix[
matrix of nodes,
nodes={draw=black,inner sep=4pt,rounded corners=1mm},
row sep=.5cm, column sep=1cm,
] (m) {
Molecular & Diamond \\
Amorphous & Sodium \\
Metallic & Carbon Dioxide \\
Covalent Network & Glass \\
};
\draw (m-1-1.east) -- (m-3-2.west);
\draw (m-2-1.east) -- (m-4-2.west);
\draw (m-3-1.east) -- (m-2-2.west);
\draw (m-4-1.east) -- (m-1-2.west);
\end{tikzpicture}
\end{document}