【问题标题】:Adding edge weights to TikZ using \draw syntax使用 \draw 语法向 TikZ 添加边权重
【发布时间】:2019-11-07 02:38:23
【问题描述】:

我有以下使用 TikZ 的图表:

\begin{tikzpicture}
        \tikzset{vertex/.style = {shape=circle,draw,minimum size=2em}}
        \tikzset{edge/.style = {->,> = latex'}}
        % Vertices
        \node[vertex] (s) at (0,0) {s};
        \node[vertex] (t) at (2,-2) {t};
        \node[vertex] (v) at (-2,-2) {v};
        \node[vertex] (w) at (2,-5) {w};
        \node[vertex] (u) at (-2,-5) {u};
        % Edges
        \draw[edge, ultra thick] (s) to (t);
        \draw[edge, ultra thick] (s) to (v);
        \draw[edge, ultra thick] (t) to (w);
        \draw[edge, ultra thick] (v) to (u);
        \draw[edge] (t) to (u);
        \draw[edge] (v) to (w);
\end{tikzpicture}

使用这种语法向该图添加边权重的最佳方法是什么?

【问题讨论】:

标签: latex tikz


【解决方案1】:

您可以简单地将节点添加到路径。这可以通过以下任一方式完成

\draw (x) -- (y) node [midway] {w} ;

如果您使用标准语法来绘制边缘。或与

\draw (x) -- to node[] {w} (y)  ;

如果您更喜欢“to”形式。

节点的正常位置是直线的正中间,但您可以添加任何参数来调整节点的位置(左、右、上、下或 x/yshift)。

此节点也可以遵循边缘方向(倾斜)。在这种情况下,参数是根据边缘方向定义的,您将主要使用上面或下面。

这是一个使用正常或倾斜权重的示例。我使用了“to”和“--”两种形式。

\documentclass{article}

\usepackage{tikz}
\usetikzlibrary{arrows.meta}

\begin{document}

\begin{tikzpicture}[
  vertex/.style = {shape=circle,draw,minimum size=2em},
  edge/.style = {->,-Latex},
  ]
  % Vertices
  \node[vertex] (s) at (0,0) {s};
  \node[vertex] (t) at (2,-2) {t};
  \node[vertex] (v) at (-2,-2) {v};
  \node[vertex] (w) at (2,-5) {w};
  \node[vertex] (u) at (-2,-5) {u};
  % Edges
  \draw[edge, ultra thick] (s) -- (t) node[midway,right] {$w_{st}$}  ;
  \draw[edge, ultra thick] (s) to node[left] {$w_{sv}$} (v);
  \draw[edge, ultra thick] (t) to node[right] {$w_{tw}$} (w);
  \draw[edge, ultra thick] (v) to  node[left] {$w_{vu}$} (u);
  \draw[edge] (t) to node[above, xshift=8mm] {$w_{tu}$} (u);
  \draw[edge] (v) to node[above, xshift=-8mm]  {$w_{vw}$} (w);
\end{tikzpicture}
\hfill%
\begin{tikzpicture}[
  vertex/.style = {shape=circle,draw,minimum size=2em},
  edge/.style = {->,-Latex},
  ]
  % Vertices
  \node[vertex] (s) at (0,0) {s};
  \node[vertex] (t) at (2,-2) {t};
  \node[vertex] (v) at (-2,-2) {v};
  \node[vertex] (w) at (2,-5) {w};
  \node[vertex] (u) at (-2,-5) {u};
  % Edges
  \draw[edge, ultra thick] (s) -- (t) node[midway,above,sloped] {$w_{st}$}  ;
  \draw[edge, ultra thick] (s) to node[above,sloped] {$w_{sv}$} (v);
  \draw[edge, ultra thick] (t) to node[above,sloped] {$w_{tw}$} (w);
  \draw[edge, ultra thick] (v) to  node[below,sloped] {$w_{vu}$} (u);
  \draw[edge] (t) to node[above left, sloped] {$w_{tu}$} (u);
  \draw[edge] (v) to node[above right, sloped]  {$w_{vw}$} (w);
\end{tikzpicture}
\end{document}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-24
    • 1970-01-01
    相关资源
    最近更新 更多