在下面的 MWE 中,我想将标签“10”稍微向上移动一点,这样它就不会与从 B 到 D 的线重叠。stackexchange 上有几个关于边缘标签定位的问题,但大多数是关于沿着边缘移动它(使用pos
)。这个提出了一种解决方案,使用inner sep
和outer sep
,和/或更改标签节点的形状,但这也会改变水平位置。我不想这样做,因为我希望标签与上方边缘的标签“3”对齐。
\documentclass[border=5]{standalone}
\usepackage{tikz}
\usetikzlibrary{positioning}
\usetikzlibrary{calc}
\tikzset{stage/.style={draw,minimum width=15mm,minimum height=7mm}}
\begin{document}
\begin{tikzpicture}
\node [stage] (A) {A};
\node [stage] (B) at ($ (A) +(3cm,0cm) $) {B};
\node [stage] (C) at ($ (B) +(0cm,2cm) $) {C};
\node [stage] (D) at ($ (B) +(3cm,1cm) $) {D};
\path[->] (A.east) edge node[above,at start,anchor=south west] {\small 2} (B.west);
\path[->] (C.east) edge node[above,at start,anchor=south west] {\small 3} (D.170);
\path[->] (B.east) edge node[above,at start,anchor=south west] {\small 10} (D.190);
\end{tikzpicture}
\end{document}
有什么建议吗?
答案1
像这样吗?
我刚刚添加yshift=5pt
到节点。
\path[->] (B.east) edge node[above,at start,anchor=south west, yshift=5pt] {\small 10} (D.190);
如果您想将其向下移动,只需将其设为负尺寸。
\path[->] (B.east) edge node[above,at start,anchor=south west, yshift=-5pt] {\small 10} (D.190);
代码:
\documentclass[border=10pt,tikz]{standalone}
\usetikzlibrary{positioning,calc}
\tikzset{stage/.style={draw,minimum width=15mm,minimum height=7mm}}
\begin{document}
\begin{tikzpicture}
\node [stage] (A) {A};
\node [stage] (B) at ($ (A) +(3cm,0cm) $) {B};
\node [stage] (C) at ($ (B) +(0cm,2cm) $) {C};
\node [stage] (D) at ($ (B) +(3cm,1cm) $) {D};
\path[->] (A.east) edge node[above,at start,anchor=south west] {\small 2} (B.west);
\path[->] (C.east) edge node[above,at start,anchor=south west] {\small 3} (D.170);
\path[->] (B.east) edge node[above,at start,anchor=south west, yshift=5pt] {\small 10} (D.190);
\end{tikzpicture}
\end{document}
答案2
基本问题已经通过 cfr 答案解决,因此我想指出以稍微不同的方式编写代码的一些可能性:
- 由于你加载了 TikZ 库定位,因此在节点定位中使用它们
- 定义边缘节点的样式(它们具有相同的选项),还定义节点的字体大小
- 使用选项
auto
进行边缘节点定位 - 将线绘制为路径段
完整代码:
\documentclass[border=5,tikz]{standalone}
\usetikzlibrary{calc,
positioning}
\tikzset{stage/.style = {draw,minimum width=15mm,minimum height=7mm},
edgenode/.style = {font=\small,near start}}
\begin{document}
\begin{tikzpicture}[
node distance = 3mm and 12mm,
auto,
]
\node (A) [stage] {A};
\node (B) [stage,right=of A] {B};
\node (D) [stage,above right=of B] {D};
\node (C) [stage,above left=of D] {C};
%
\path[->] (A) edge node[edgenode] {2} (B)
(C.east) edge node[edgenode] {3} (D.170)
(B.east) edge node[edgenode,xshift=2mm] {10} (D.190);
\end{tikzpicture}
\end{document}
获得的图像与 cfr 答案几乎相同:
在这种情况下,边缘节点可以放置在线的中间(以 edgenode
擦除的样式near start
),然后不再需要校正“10”的定位。