Enter a line break in node text in Latex Tikz library

user1718097 picture user1718097 · Jun 1, 2015 · Viewed 19k times · Source

I've just started using Latex to produce a maths-heavy document. I wanted to include a probability tree and found the Tikz library. The first bit of the code for my tree looks like:

%To create probability trees, use tikz package
\usepackage{tikz}
\usetikzlibrary{trees}

% Insert a probability tree showing first level only
% -------------------------------------------------------------
% Set the overall layout of the tree
\tikzstyle{level 1}=[level distance=3.5cm, sibling distance=4.0cm]
\tikzstyle{level 2}=[level distance=3.5cm, sibling distance=2cm]

% Define styles for bags and leafs
\tikzstyle{bag} = [text centered]

% Draw probability tree
\begin{tikzpicture}[grow=right, sloped]
\node[bag] {}
    child {
        node[bag] {Not diseased $\left( D^- \right)$}
            edge from parent 
            node[below]  {$0.90$}
    }
    child {
        node[bag] {Diseased $\left( D^+ \right)$}        
            edge from parent         
            node[above] {Prevalence}
            node[below]  {$0.10$}
    };
\end{tikzpicture} \\

The resulting tree looks a bit like this:

             Diseased (D+)
           /
    Prev /
       / 0.10
     /
     \
       \
   0.90  \
           \
             Not diseased (D-)

... if you get my drift.

I would like to be able to enter a line break in the node text so that the (D+) and (D-) appear underneath. I've tried using \\ and \newline but to no avail. Any suggestions?

Thanks in advance.

Answer

MattAllegro picture MattAllegro · Jun 30, 2015

Starting from your code,

\documentclass[multi=false,border=2mm]{standalone}
\usepackage{tikz}
\usetikzlibrary{trees}

\tikzstyle{level 1}=[level distance=3.5cm, sibling distance=4.0cm]
\tikzstyle{level 2}=[level distance=3.5cm, sibling distance=2cm]

\tikzstyle{bag} = [align=center]

\begin{document}

\begin{tikzpicture}[grow=right, sloped]
\node[bag] {}
    child {
        node[bag] {Not diseased\\ $\left( D^- \right)$} %% 1
            edge from parent
            node[below]  {$0.90$}
    }
    child {
        node[bag] {Diseased\\ $\left( D^+ \right)$} %% 2
            edge from parent
            node[above] {Prevalence}
            node[below]  {$0.10$}
    };
\end{tikzpicture}

\end{document}

makes the job: notice that I only changed \tikzstyle{bag} from [text centered] to [align=center] and added \\ in lines marked %% 1 and %% 2.

The resulting tree:

output pdf