Search code examples
rshinyheatmapheatmaply

How can I plot a heatmap with the heatmaply package in Shiny?


I am trying to use the heatmaply package in order to plot a heatmap and it works well.

On the other hand, when I try to do the same plot in Shiny it doesn't appear in the interface (when I click "run app"). However, when I close the window suddenly the plot appears in the R viewer. Is it possible that the heatmaply package doesn't work with Shiny?

This is my code, when I plot it in R.

library(heatmaply)
x  <- as.matrix(datasets::mtcars)
rc <- colorspace::rainbow_hcl(nrow(x))

heatmaply(
  x[, -c(8, 9)],
  col_side_colors = rc[1:9],
  showticklabels=FALSE,
  Rowv = TRUE,
  Colv = FALSE
)

This is my code in Shiny.

library(shiny)
library(heatmaply)

ui <- fluidPage(

    # Application title
    titlePanel("Heatmap"),

    sidebarLayout(
        sidebarPanel(
            
        ),

        # Show a plot of the generated distribution
        mainPanel(
           plotOutput("distPlot")
        )
    )
)
x  <- as.matrix(datasets::mtcars)
rc <- colorspace::rainbow_hcl(nrow(x))

server <- function(input, output) {

    output$distPlot <- renderPlot({
        heatmaply(
          x[, -c(8, 9)],
          col_side_colors = rc[1:9],
          showticklabels=FALSE,
          Rowv = TRUE,
          Colv = FALSE
        )

     })
}

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

I have tried another packages to have an interactive heatmap but it is the only one that it has what I want, so for that reason I need to ask here if someone knows how to use it in Shiny.

Thanks in advance,

Regards


Solution

  • You can use plotlyOutput and renderPlotly :

    library(shiny)
    library(heatmaply)
    library(plotly)
    
    ui <- fluidPage(
      
      # Application title
      titlePanel("Heatmap"),
      
      sidebarLayout(
        sidebarPanel(
          
        ),
        
        # Show a plot of the generated distribution
        mainPanel(
          plotlyOutput("distPlot")
        )
      )
    )
    x  <- as.matrix(datasets::mtcars)
    rc <- colorspace::rainbow_hcl(nrow(x))
    
    server <- function(input, output) {
      
      output$distPlot <- renderPlotly({
        heatmaply(
          x[, -c(8, 9)],
          col_side_colors = rc[1:9],
          showticklabels=FALSE,
          Rowv = TRUE,
          Colv = FALSE
        )
        
      })
    }
    
    # Run the application 
    shinyApp(ui = ui, server = server) 
    

    enter image description here

    Also there is a package shinyHeatmaply which might be of interest.