dynamically add layers to a ggtree/ggplot in rshiny


I am attempting to dynamically add layers to a phylogenetic tree shiny app.
The code below will allow the user to brush tree tips and then add an annotation ('label') to the tree image. However, what I want is to keep the tree image with the annotation and then be able to add another annotation. Currently, the tree image and annotation is written over when I move the brushed selection.

Any tips or suggestions for how to store the tree image with annotation and add to that would be greatly appreciated.


#make phylogenetic tree
text.string <-"(((((((cow, pig),whale),(bat,(lemur,human))),(robin,iguana)),coelacanth),gold_fish),shark);"

#read in the tree

# Define UI for application that draws a histogram
ui <- fluidPage(
  # Application title
  actionButton("add_annotation","Add clade annotation"),
  # Show a plot of the generated distribution
  mainPanel(plotOutput("treeDisplay", brush ="plot_brush")

# Define server logic required to draw a histogram
server <- function(input, output) {
  #reactive that holds base tree - this is how I am building the base tree 
  make_tree <- reactive({
      ggplot2::xlim(NA, 10)})
  #render base tree 
  output$treeDisplay <- renderPlot({
  #reactive that holds the brushed points on a plot
  dataWithSelection <- reactive({
    brushedPoints(make_tree()$data, input$plot_brush)
  #add to label to vector if isTip == True
  dataWithSelection2 <- reactive({
    tipVector <- c()
    for (i in 1:length(dataWithSelection()$label)){ if(dataWithSelection()$isTip[i] == TRUE) tipVector <- c(tipVector,dataWithSelection()$label[i])}
  # incorporate the tipVector information for adding layer
  layer <- reactive({
    ggtree::geom_cladelabel(node=phytools::findMRCA(ape::as.phylo(make_tree()), dataWithSelection2()), label = "Clade", color = "red")
  #display that layer onto the tree
  observeEvent(input$add_annotation, {
    output$treeDisplay <- renderPlot({make_tree() + layer()})

# Run the application 
shinyApp(ui = ui, server = server)

This topic was automatically closed 54 days after the last reply. New replies are no longer allowed.