Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enter a line break in node text in Latex Tikz library

Tags:

latex

tikz

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.

like image 277
user1718097 Avatar asked Jun 01 '15 16:06

user1718097


1 Answers

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

like image 99
MattAllegro Avatar answered Sep 17 '22 21:09

MattAllegro