在Tikz中,如何使邊緣上的文字與邊緣的方向相同?

在Tikz中,如何使邊緣上的文字與邊緣的方向相同?

我創建了一個簡單的節點邊圖,其中我希望每條邊上的文字與邊的方向對齊。

\documentclass[class=minimal,border=0pt]{standalone}
\usepackage{pgf}
\usepackage{tikz}
\usetikzlibrary{arrows,automata}
\usepackage[latin1]{inputenc}
\begin{document}

\begin{tikzpicture}[->,>=stealth',shorten >=1pt,auto,node distance=2.8cm,
                    semithick]
  \tikzstyle{every state}=[fill=red,draw=none,text=white]

  \node[state]         (D)                     {$D$};
  \node[state]         (C) [below right of=D]  {$C$};
  \node[state]         (B) [above right of=D]  {$B$};
  \node[state]         (A) [below right of=B]  {$A$};

  \path (D) edge              node {tdc} (C)            
        (B) edge              node {tbc} (C)
        (C) edge              node {tca} (A);
\end{tikzpicture}

\end{document}

例如,我希望文字自動tbc旋轉度數以與連接節點到節點的-90邊緣方向對齊。那可能嗎?BC

答案1

如何讓文本走的問題的答案沿著路徑是使用sloped密鑰。這會旋轉節點以符合節點放置點處的路徑切線(請參閱 PGF 手冊第 16.8 節)。

然而,正如評論中所指出的,這並不完全符合預期。這是因為auto鑰匙。這會將節點移離路徑。它透過將節點錨點之一放置在放置點來實現這一點,該錨點是根據路徑的切線適當選擇的(我沒有查看程式碼,所以我猜測它是如何選擇的)。問題在於先選擇錨點,然後旋轉節點。應該發生的事情是旋轉節點,然後選擇錨點。但實際上,這不需要任何複雜的程式碼,因為錨點始終是northor之一south(如果allow upside down設定了,那麼它將始終是south)。所以只需設定anchor=south而不是就auto可以了。

這是一個簡單的例子來示範上述分析。前三個節點不是sloped,後三個節點是。三元組中的第一個沒有(其他)選項,第二個是,auto第三個是anchor=south。從第二個和第五個可以清楚地看出,節點已有效地圍繞其錨點旋轉。

節點旋轉到路徑

這是經過此更改的程式碼(加上一些小的風格變更:自動tikz加載pgf,並且\tikzstyle已棄用)。

\documentclass{standalone}
%\url{http://tex.stackexchange.com/q/67552/86}
\usepackage{tikz}
\usetikzlibrary{arrows,automata}
\usepackage[latin1]{inputenc}
\begin{document}
\begin{tikzpicture}[
  ->,
  >=stealth',
  shorten >=1pt,
  auto,
  node distance=2.8cm,
  semithick,
  every state/.style={fill=red,draw=none,text=white},
]
  \node[state]         (D)                     {$D$};
  \node[state]         (C) [below right of=D]  {$C$};
  \node[state]         (B) [above right of=D]  {$B$};
  \node[state]         (A) [below right of=B]  {$A$};

  \path[every node/.style={sloped,anchor=south,auto=false}]
        (D) edge              node {tdc} (C)            
        (B) edge              node {tbc} (C)
        (C) edge              node {tca} (A);
\end{tikzpicture}
\end{document}

(注意,這auto=false不是必需的,因為它anchor=south會覆蓋auto密鑰)

結果如下:

提問者的圖片,附箭頭文字

相關內容