Skip to content

Instantly share code, notes, and snippets.

@gluc
Created April 28, 2016 18:31
Show Gist options
  • Save gluc/bdfdbe410ce808aa488c6a01a4b43aa5 to your computer and use it in GitHub Desktop.
Save gluc/bdfdbe410ce808aa488c6a01a4b43aa5 to your computer and use it in GitHub Desktop.
How to plot with data.tree to a pdf file?
#How to plot data.tree to PDF?
#This was tested with data.tree 0.3.6
#Various options
library(data.tree)
data(acme)
# 1. ape package
library(ape)
plot(as.phylo(acme))
# 2. igraph package
library(igraph)
plot(as.igraph(acme))
# 3. dendrogram
plot(as.dendrogram(acme))
# 4. advanced ape example
library(yaml)
fileName <- filePath <- system.file("extdata", "jennylind.yaml", package="data.tree")
l <- yaml.load_file(fileName)
jl <- as.Node(l)
print(jl, "type", "payoff", "p")
payoff <- function(node) {
if (node$type == 'chance') node$payoff <- sum(sapply(node$children, function(child) child$payoff * child$p))
else if (node$type == 'decision') node$payoff <- max(sapply(node$children, function(child) child$payoff))
}
jl$Do(payoff, traversal = "post-order", filterFun = isNotLeaf)
decision <- function(x) {
po <- sapply(x$children, function(child) child$payoff)
x$decision <- names(po[po == x$payoff])
}
jl$Do(decision, filterFun = function(x) x$type == 'decision')
#Plotting
library(ape)
jl$Revert()
jlp <- as.phylo(jl)
Nodelabel <- function(node) {
po <- paste0( '$ ', format(node$payoff, scientific = FALSE, big.mark = "'"))
if (node$type == 'terminal') return (po)
return ( paste0('ER\n', po) )
}
par(mar=c(1,1,1,1))
plot(jlp, show.tip.label = FALSE, type = "cladogram")
#We set arrow heads to the leaf-edges:
for (node in jl$leaves) edges(GetPhyloNr(node$parent, "node"),
GetPhyloNr(node, "node"),
arrows = 2,
type = "triangle",
angle = 60)
#Finally, we iterate over all the nodes and print the labels. Note that the `GetPhyloNr`
#methods lets us map a `Node` in the data.tree to its counterpart in the phylo object.
for(node in Traverse(jl)) {
if(node$type == 'decision') {
nodelabels(Nodelabel(node), GetPhyloNr(node, "node"), frame = 'none', adj = c(0.3, -0.5))
} else if(node$type == 'chance') {
if (node$name == node$parent$decision) edges(GetPhyloNr(node$parent, "node"),
GetPhyloNr(node, "node"), col = "red")
nodelabels(" ", GetPhyloNr(node, "node"), frame = "circle")
nodelabels(Nodelabel(node), GetPhyloNr(node, "node"), frame = 'none', adj = c(0.5, -0.5))
edgelabels(node$name, GetPhyloNr(node, "edge"), bg = "white")
} else if(node$type == 'terminal') {
tiplabels(Nodelabel(node), GetPhyloNr(node, "node"), frame = "none", adj = c(0.5, -0.6))
edgelabels(paste0(node$name," (", node$p, ")"), GetPhyloNr(node, "edge"), bg = "white")
}
}
nodelabels(" ", GetPhyloNr(jl, "node"), frame = "rect")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment