Search code examples
rggtree

How can I get ggtree::geom_range to work?


I am trying to add range bars to nodes as described in the treedata book. Here is an example from the book of what I am trying to achieve:

trees with bars

Note the red bars.

Here is code that should create a tree image with red bars:

library(tidyverse)
library(treeio)
library(ggtree)

# create a tree and add a numeric annotation called 'range'
tree = rtree(3) %>% as.treedata %>% as_tibble %>% 
  mutate(range=0.1) %>% 
  as.treedata

# plot the tree and add red bars with geom_bar()
ggtree(tree)  + geom_range(range='range', color="red")

tree without bars

However, the resulting plot does not have red bars.

What do I need to do in order to add red bars to every node?

I am using ggtree v2.2.4, treeio v1.12.0, and ggplot2 v3.3.2.


Solution

  • You are only giving a single value to range. In the example you linked, the column range is a list, where each row contains a minimum and maximum value. So you probably want something like:

    library(tidyverse)
    library(treeio)
    library(ggtree)
    
    # create a tree and add a numeric annotation called 'range'
    tree = rtree(3) %>% as.treedata %>% as_tibble %>% 
      mutate(number = 1:5,
            range = lapply(number, function(x) c(-0.1, 0.1) + x)) %>% 
      as.treedata
    
    # plot the tree and add red bars with geom_bar()
    ggtree(tree)  + 
      geom_range("number", range='range', color="red", size = 3, alpha = 0.3) + 
      theme_tree2()
    

    enter image description here