覆盖 TikZ 在图中自动放置权重

覆盖 TikZ 在图中自动放置权重

所以我有以下图表:

\documentclass{article}
\usepackage{amsmath}
\usepackage{tikz}
\usepackage[english]{babel}
\begin{document}

\tikzstyle{vertex}=[draw=black!25,shape=circle,fill=black!25, edge=black!25,minimum size=20pt,inner sep=0pt]
\tikzstyle{edge} = [draw,thick,-]
\tikzstyle{arrow} =[draw,thick,->]
\tikzstyle{weight} = [font=\scriptsize]

\begin{tikzpicture}[scale=2,auto,swap]
\foreach \pos /\name in {{(0,0)}/1,{(1,1)}/3,{(0,2)}/2,{(2,2)}/4,{(2,1)}/5}
   \node[vertex](\name) at \pos{$\name$};
\foreach \source /\dest /\weight in {1/3/1,1/5/2,2/1/5,3/2/2,3/5/3,4/2/8,5/2/7,5/4/5} 
   \path[arrow] (\source) -- node[weight] {$\weight$} (\dest);
\foreach \source /\dest /\weight in {1/3/1} place \weight above of=\path[arrow];
\end{tikzpicture}
\end{document}

得到下图:

在此处输入图片描述

如您所见,重量的自动放置并不理想。箭头重量从 1 到 3 和箭头重量从 3 到 2 最好分别放置在箭头上方和下方。有没有办法“覆盖”自动放置,而不必手动定义所有重量位置?即:我可以告诉将特定重量放置在其他位置吗?

谢谢!

答案1

您可以创建两个foreach循环,并且只指定您想要更改的位置:

\documentclass{article}
\usepackage{amsmath}
\usepackage{tikz}
\usepackage[english]{babel}
\begin{document}

\tikzstyle{vertex}=[draw=black!25,shape=circle,fill=black!25, edge=black!25,minimum size=20pt,inner sep=0pt]
\tikzstyle{edge} = [draw,thick,-]
\tikzstyle{arrow} =[draw,thick,->]
\tikzstyle{weight} = [font=\scriptsize]

\begin{tikzpicture}[scale=2,auto,swap]
    \foreach \pos /\name in {{(0,0)}/1,{(1,1)}/3,{(0,2)}/2,{(2,2)}/4,{(2,1)}/5}
        \node[vertex](\name) at \pos{$\name$};
    \foreach \source /\dest /\weight in {1/5/2,2/1/5,3/5/3,4/2/8,5/2/7,5/4/5} 
        \path[arrow] (\source) -- node[weight] {$\weight$} (\dest);
    \foreach \source /\dest /\weight/\pos in {1/3/1/{above left}, 3/2/2/{below left}} 
        \path[arrow] (\source) -- node[weight, \pos] {$\weight$} (\dest);
\end{tikzpicture}


\end{document}

加权图

答案2

您可以将重量放在边缘的中间,白色背景内(这并非对您的问题的准确回答):

\documentclass{article}
\usepackage{amsmath}
\usepackage{tikz}
\usepackage[english]{babel}
\begin{document}

\tikzstyle{vertex}=[draw=black!25,shape=circle,fill=black!25, edge=black!25,minimum size=20pt,inner sep=0pt]
\tikzstyle{edge} = [draw,thick,-]
\tikzstyle{arrow} =[draw,thick,->]
\tikzstyle{weight} = [draw=none,fill=white,inner sep=1pt,font=\scriptsize]

\begin{tikzpicture}[scale=2,swap]
\foreach \pos /\name in {{(0,0)}/1,{(1,1)}/3,{(0,2)}/2,{(2,2)}/4,{(2,1)}/5}
   \node[vertex](\name) at \pos{$\name$};
\foreach \source /\dest /\weight in {1/3/1,1/5/2,2/1/5,3/2/2,3/5/3,4/2/8,5/2/7,5/4/5} 
   \path[arrow] (\source) -- node[weight] {$\weight$} (\dest);
\foreach \source /\dest /\weight in {1/3/1} place \weight above of=\path[arrow];
\end{tikzpicture}
\end{document}

pdflatex 输出

相关内容