# Newline or line break in Tikz

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:

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?

• Try \path[->](L) edge node [sloped, above, align=center] {$S$\\ $R\left(L, S, M\right) = -1$} (M); – Zarko May 28 at 18:38
• I tried your suggestion, and it worked. When I tried \newline, nothing happened. How come? – Superman May 28 at 18:41
• The difference is align=center. – user194703 May 28 at 18:42

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}


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}


• 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 at 19:21