library(ape)

plot.tree.custom = function(tree,col="grey"){ 
    par(mar=c(0,1,0,1),xpd=NA)
    plot(tree,type="unrooted",edge.width=6,edge.color=col,show.tip.label=F,no.margin=T)
    tiplabels(text=c(unlist(names[tree$tip.label[1:2]]),rep("",2)),bg="white",frame="none",col=unlist(colors[tree$tip.label]),cex=2,adj=c(0,1))
    tiplabels(text=c(rep("",2),unlist(names[tree$tip.label[3:4]])),bg="white",frame="none",col=unlist(colors[tree$tip.label]),cex=2,adj=c(0,0))
} 

probs = as.matrix(read.table("4_globins_topo.probs"))
ord = rev(order(probs[,3]))
tree.1 = read.tree("tree1.nwk")
tree.2 = read.tree("tree2.nwk")
tree.3 = read.tree("tree3.nwk")

probs.minRisk = as.matrix(read.table("4_globins_MinRisk_topo.probs"))

postscript(file="4_globin_posterior_barplot.eps",height=6,width=16,onefile=F,horizontal=F)

layout(matrix(c(rep(7,2),rep(1,2),rep(7,2),rep(2,2),rep(7,2),rep(3,2),rep(7,2),3+c(rep(1,12),2,3)),2,14,byrow=T))
colors = list("1lh1"="limegreen","2hhba"="red","1urva"="orange","2mm1"="blue")
names = list("1lh1"="LegHb","2hhba"="HbA","1urva"="Cygb","2mm1"="Mb")
plot.tree.custom(tree.1,grey.colors(3)[1])
plot.tree.custom(tree.2,grey.colors(3)[2])
plot.tree.custom(tree.3,grey.colors(3)[3])
par(mar=c(4,5,0,0))
barplot(t(probs[ord,3:1]),border='NA',space=0,ylab="Mean posterior for topology",cex.lab=1.5,cex.axis=1.5)
axis(side=1,at=50,labels="Alignment samples",padj=0.5,tick=F,cex.axis=1.5)
par(mar=c(4,0,0,2))
barplot(matrix(apply(probs[ord,3:1],2,mean),3,1),border='NA',space=0,xaxt='n',yaxt='n')
axis(side=1,at=0.5,labels="Mean",padj=0.5,tick=F,cex.axis=1.5); par(mar=c(4,0,0,2))
barplot(apply(probs.minRisk,1,rev),border='NA',space=0,xaxt='n',yaxt='n')
axis(side=1,at=0.5,labels="DAG",padj=0.5,tick=F,cex.axis=1.5)

dev.off()
