2

So I am trying to follow this this link to break up the text in two lines. Here is my code:


\documentclass[12pt]{article}
\usepackage{float}
\usepackage[margin=1in]{geometry}
\usepackage{tikz}
\usetikzlibrary{shapes, arrows.meta, automata, calc}

\begin{document} 
    \begin{figure}[H]\centering
        \begin{tikzpicture}[node distance=2cm, >= Stealth, auto, shorten >= 1pt]
            \node[state](L){$L$};
            \node[state] at ($(L)+(60:4cm + 2.5em)$)(M) {$M$};
            \node[state] at ($(M)+(-60:4cm+ 2.5em)$)(H) {$H$};  
            \path[->](L) edge node [sloped, above] {$S$ \newline $R\left(L, S, M\right) = -1$} (M);
        \end{tikzpicture}
    \end{figure}
\end{document}

Output:

enter image description here

I tried the \\ command, but I get an error. How to fix it and make sure that the text gets broken up in two lines?

Superman
  • 1,615

2 Answers2

4

This is a version using the angled style from my previous answer. Whenever you want to allow for a line break in a node, you need to add some alignment (such as align=left) or some text width.

\documentclass[12pt]{article}
\usepackage{float}
\usepackage[margin=1in]{geometry}
\usepackage{tikz}
\usetikzlibrary{arrows.meta,automata, positioning,calc}
\tikzset{angled/.style args={#1 and #2 of #3}{%
at={($(#3.#1)+(#1:#2)$)},anchor={#1+180}}}
\begin{document} 
    \begin{figure}[H]\centering
        \begin{tikzpicture}[node distance=4cm,>=stealth]
            \node[state](L){$L$};
            \node[angled=60 and 4cm of L,state] (M) {$M$};
            \node[state,right=of L] (H) {$H$};
            \path[->](L) edge node [sloped, above,align=center] 
            {$S$\\ $R\left(L, S, M\right) = -1$} (M);
        \end{tikzpicture}
    \end{figure}
\end{document}

enter image description here

  • Lifesaver! Was banging my head off a wall for a day on this...any link to a reference in the PGF Manual? AKA what did I miss?! – Colin Dec 09 '21 at 01:07
3

Why you nest float in float?

Nodes, which can contain multi line text hat have defined either text width and align=... (for formatting text in node) for automatic break node contents (if it is possible) or just align=... for manual breaking. For it you need to use \\ line termination. So your MWE should be:

\documentclass[12pt]{article}
\usepackage[margin=1in]{geometry}
\usepackage{tikz}
\usetikzlibrary{arrows.meta, automata, calc, shapes}

\begin{document}
\begin{figure}[ht]
\centering
    \begin{tikzpicture}[>= Stealth, shorten >= 1pt]
    \node[state](L){$L$};
    \node[state] at ($(L)+(60:4cm + 2.5em)$)(M) {$M$};
    \node[state] at ($(M)+(-60:4cm+ 2.5em)$)(H) {$H$};
    \path[->](L) edge node [sloped, above, align=center] {$S$\\ $R(L,S,M)=-1$} (M);
    \end{tikzpicture}
\end{figure}
\end{document}

enter image description here

Zarko
  • 296,517
  • I realized that I had a figure in figure, so I removed it. I was copying and pasting code, so I overlooked the extra figure. – Superman May 28 '20 at 19:21