我正在尝试根据节点坐标自动生成图纸。构造过程本身非常简单:从节点 i 到节点 i+1 画一个箭头(i 和 i+1 为节点名称,事先已修复,我不想修改)。棘手的部分是节点可以以任何顺序排列在一条线上,我希望所有圆弧都绘制在水平线上方。我曾尝试提取x
节点的坐标并使用以下方法进行比较,但没有成功\ifnumcomp
:
\documentclass{article}
\usepackage{etoolbox}
\usepackage{tikz}
\begin{document}
This is fine:
\begin{tikzpicture}
% node placement
\node[circle,draw,inner sep=2pt] (0) at (0, 0) [label=below:0] {};
\node[circle,draw,inner sep=2pt] (1) at (1, 0) [label=below:1] {};
\node[circle,draw,inner sep=2pt] (2) at (2, 0) [label=below:2] {};
\foreach [count=\q from 0] \p in {1, 2}
\draw[->,>=stealth] (\q) to [bend left=60] (\p);
% arcs
\end{tikzpicture}
This is not fine:
\begin{tikzpicture}
% node placement
\node[circle,draw,inner sep=2pt] (0) at (0, 0) [label=below:0] {};
\node[circle,draw,inner sep=2pt] (2) at (1, 0) [label=below:2] {};
\node[circle,draw,inner sep=2pt] (1) at (2, 0) [label=below:1] {};
\foreach [count=\q from 0] \p in {1, 2}
\draw[->,>=stealth] (\q) to [bend left=60] (\p);
% arcs
\end{tikzpicture}, I want it to look like this: \begin{tikzpicture}
% node placement
\node[circle,draw,inner sep=2pt] (0) at (0, 0) [label=below:0] {};
\node[circle,draw,inner sep=2pt] (2) at (1, 0) [label=below:2] {};
\node[circle,draw,inner sep=2pt] (1) at (2, 0) [label=below:1] {};
% \foreach [count=\q from 0] \p in {1, 2}
\draw[->,>=stealth] (0) to [bend left=60] (1);
\draw[->,>=stealth] (1) to [bend right=60] (2);
% arcs
\end{tikzpicture}
This attempt at combining \verb|\ifnumcomp| and \verb|\pgfextractx| fails:
\begin{tikzpicture}
% node placement
\node[circle,draw,inner sep=2pt] (0) at (0, 0) [label=below:0] {};
\node[circle,draw,inner sep=2pt] (2) at (1, 0) [label=below:2] {};
\node[circle,draw,inner sep=2pt] (1) at (2, 0) [label=below:1] {};
\foreach [count=\q from 0] \p in {1, 2} {
\newdimen\px
\newdimen\qx
\pgfextractx{\px}{\p}
\pgfextractx{\qx}{\q}
\ifnumcomp{\qx}{<}{\px}{
\draw[->,>=stealth] (\q) to [bend left=60] (\p);
}{
\draw[->,>=stealth] (\q) to [bend right=60] (\p);
}
}
% arcs
\end{tikzpicture}
\end{document}
该文件内容如下:
我该如何修复我尝试的解决方案?(或者有人知道“更好”/“更简单”/......的解决方案?)
(为了使图纸看起来更好,弯曲角度应该与节点之间的距离成比例,但我想这应该是一个单独的问题)。
答案1
使用Andrew Stacey 的回答到相关问题允许我获得想要的结果。这是一个完整的工作示例:
\documentclass{article}
\usepackage{etoolbox}
\usepackage{tikz}
% Andrew Stacey's code:
\makeatletter
\newcommand{\gettikzxy}[3]{%
\tikz@scan@one@point\pgfutil@firstofone#1\relax
\edef#2{\the\pgf@x}%
\edef#3{\the\pgf@y}%
}
\makeatother
\begin{document}
\begin{tikzpicture}
% node placement
\node[circle,draw,inner sep=2pt] (0) at (0, 0) [label=below:0] {};
\node[circle,draw,inner sep=2pt] (2) at (1, 0) [label=below:2] {};
\node[circle,draw,inner sep=2pt] (1) at (2, 0) [label=below:1] {};
% arcs
\foreach [count=\q from 0] \p in {1, 2} {
\gettikzxy{(\p)}{\px}{\py}
\gettikzxy{(\q)}{\qx}{\qy}
\ifdimcomp{\qx}{<}{\px}{
\draw[->,>=stealth] (\q) to [bend left=60] (\p);
}{
\draw[->,>=stealth] (\q) to [bend right=60] (\p);
}
}
\end{tikzpicture}
\end{document}