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

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

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)
Also there is a package shinyHeatmaply which might be of interest.

Related

Shiny and parallel package

I'm writing a shiny app, which runs a function over a set of parameters, so I figured I could use multiple cores.
For some reason it can't feed in the variables to the cluster, I get an error: "var_mean" not found. I've tried isolate but that didn't seem to help.
The code below is a very simple example which reproduces the behaviour.
Thanks for any help.
library(shiny)
library(parallel)
ui <- fluidPage(
# Application title
titlePanel("Test parallel in Shiny app"),
# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(
numericInput("n","N",value = 100),
numericInput("mean","Mean",value = 1000),
checkboxInput("parallel","Parallel?",value=FALSE)
),
# Show a plot of the generated distribution
mainPanel(
plotOutput("distPlot")
)
)
)
server <- function(input, output) {
simulate <- reactive({
mean = input$mean
sim = rnorm(input$n,mean=mean,sd = 100)
return(sim)
})
p_simulate<-reactive({
cl = makeCluster(detectCores()-1)
var_mean = input$mean
clusterExport(cl,varlist="var_mean")
sim = parSapply(cl,
1:input$n,
function(x) rnorm(1,mean=var_mean,sd = 100)
)
stopCluster(cl)
sim
})
output$distPlot <- renderPlot({
if(input$parallel){
x = p_simulate()
} else x = simulate()
# draw the histogram with the specified number of bins
hist(x)
})
}
# Run the application
shinyApp(ui = ui, server = server)
Your "clusterExport" command is missing the "envir" flag:
clusterExport(cl,varlist="var_mean", envir = environment())
That got it running for me.

Cannot display a plotly heatmap in shiny

I'm trying to display a heatmap I've made in plotly in my shiny app. I think the issue may be that I've saved it as an object.. but I don't know how else to display 2 different plots, one made in ggplot and the other in plotly.
library(shiny)
library(dplyr)
library(tidyverse)
library(magrittr)
library(DT)
library(ggplot2)
library(purrr)
library(shinythemes)
library(plotly)
#load indel histogram
Indel_histogram <- read.table(file = 'histogram.tsv',
sep = '\t', header = TRUE)
#load peddy relatedness data
Relatedness <- read.csv(file='peddy/mystudy.ped_check.csv')
###########################
# make relatedness matrix #
###########################
related_matrix <- Relatedness %>% select(sample_a, sample_b, rel)
#make comparison matrix
un2 <- sort(unique(unlist(related_matrix[1:2])))
out2_new <- related_matrix %>%
complete(sample_a = un2, sample_b = un2) %>%
pivot_wider(names_from = sample_b, values_from = rel)
tmp <- map2_dfc(data.table::transpose(out2_new, make.names = 'sample_a'),
out2_new[-1], coalesce) %>%
bind_cols(out2_new %>%
select(sample_a), .)
tmp2 <- column_to_rownames(tmp, var = "sample_a")
#heatmap in plotly format
heatmap %<>% as.matrix(tmp2)
#plot heatmap using plotly
plotly_heatmap <- plot_ly(z = heatmap, type = "heatmap")
#generate indel histogram
Indel_Histogram <- ggplot(Indel_histogram, aes(Length, Freq)) + geom_col()
##################
# Make Shiny App #
##################
ui <- fluidPage(theme = shinytheme("united"),
titlePanel("QC output"),
navbarPage("Menu",
tabPanel("Plots",
sidebarLayout(
sidebarPanel(
selectInput("more_plots", "Select Plot",
choices = c("Indel_Histogram","plotly_heatmap")), width=4),
mainPanel(plotOutput("more_plots"), height="100%", width=8))
)))
server <- function(input, output) {
output$more_plots <- renderPlot({
get(input$more_plots)
}, height=600)
}
shinyApp(ui = ui, server = server)
My code shows the Indel_histogram no problem, but is does not show the plotly_heatmap. If I run plotly_heatmap in my Rconsole, it displays for me... so I need help to get both the histogram and the heatmap to view in the same panel, when selected from the same input$moreplots.
The histogram works fine, so won't bother with that data. Here's a shortened version of heatmap:
structure(c(NA, -0.03991, -0.0249, -0.01788, -0.02618, -0.03991,
NA, -0.03303, 0.01615, 0.01119, -0.0249, -0.03303, NA, 0.009972,
0.01122, -0.01788, 0.01615, 0.009972, NA, 0.01927, -0.02618,
0.01119, 0.01122, 0.01927, NA), .Dim = c(5L, 5L), .Dimnames = list(
c("AD001", "AD002", "AD003", "AD004", "AD005"), c("AD001",
"AD002", "AD003", "AD004", "AD005")))
I then tried to render the plotly heatmap separately just to see if I could get it working... but again, doesn't display (not sure why)?
ui <- fluidPage(theme = shinytheme("united"),
titlePanel("QC output"),
navbarPage("Menu",
tabPanel("Plots",
sidebarLayout(
sidebarPanel(
selectInput("Plotly", "Select Plot",
choices = "heatmap"), width=4),
mainPanel(plotlyOutput("Plotly"), height="100%", width=8)),
)))
server <- function(input, output) {
output$Plotly <- renderPlotly(
plot_ly(z = ~get(input$Plotly), type = "heatmap")
)
}
shinyApp(ui = ui, server = server)
Something is clearly going wrong!
Assuming you have already created histogram and heatmap either outside ui or insider server function, you can try this
ui <- fluidPage(theme = shinytheme("united"),
titlePanel("QC output"),
navbarPage("Menu",
tabPanel("Plots",
sidebarLayout(
sidebarPanel(
selectInput("more_plots", "Select Plot",
choices = c("Indel_Histogram","plotly_heatmap")), width=4),
mainPanel(uiOutput("myplot"), height="100%", width=8)
)
)))
server <- function(input, output) {
output$hist <- renderPlot({
Indel_Histogram ## assuming you already did this histogram
})
output$heat <- renderPlotly({
plotly_heatmap ## assuming you already have this heatmap
})
output$myplot <- renderUI({
if (input$more_plots=="Indel_Histogram"){
plot <- plotOutput("hist", height=600)
}else plot <- plotlyOutput("heat")
})
}
shinyApp(ui = ui, server = server)

Rshiny--creation of bar plot using CSV file

I want the bar plot to be embedded into application.output of vector d is giving me result I want that to be embedded into shinyapp and later I want to make it interactive too.
library(ggplot2)
driver1 <- read.csv("E:/RMARKDOWN/shiny/driver.csv",header = T)
New_DataSet1<-
data.frame(driver1$ï..Year_AG,driver1$Severity_Desc,driver1$Injury.Type)
New_DataSet1
latest <- New_DataSet1[1:100,]
latest
d <- aggregate(latest$driver1.Injury.Type, by=list(chkID =
latest$driver1.Severity_Desc), FUN=sum)
ui <- dashboardPage(
dashboardHeader(title = "Row layout"),
dashboardSidebar(),
dashboardBody()
)
server <- function(input, output) {
#output$plot <- renderPlot({ barplot(d$x, xlab = d$chkID) })
renderPlot(d$x)
#barplot(d$x, xlab = d$chkID)
# barplot(d$x, names.arg = d$chkID)
}
shinyApp(ui,server)
You can read file first and render it using bar chart as below:
library(plotly)
library(shiny)
ui <- fluidPage(
mainPanel(
plotlyOutput("chart")
)
)
server <- function(input, output, session) {
output$chart <- renderPlotly({
# write code here to read data from csv file
df=read.csv("")
# Set x and y axis and display data in bar chart using plotly
p <- plot_ly( x = iris$Species,
y = iris$Sepal.Length,
name = "Iris data",
type = "bar")
})
}
shinyApp(ui, server)
Screenshot from working demo:

shiny - interactive ggplot with subset

I am new to R&shiny. I'd like to make a shiny app that the plot can be interactive with subset I choose, but ggplot cannot work with warning
Error in ouptut$Trendplot <- renderPlot({ : object 'ouptut' not found
It will be really appreciated if you can help to figure it works.
The following is my code:
library(shiny)
library(ggplot2)
# Define UI for application that draws a histogram
ui <- pageWithSidebar(
# Application title
headerPanel("Pre-report situation"),
# Sidebar with a slider input for number of bins
sidebarPanel(selectizeInput("DMS", "DMS:", choices = unique(datass$DMS)
)),
# Show a plot of the generated distribution
mainPanel(
h3(textOutput("caption")),
plotOutput("Trendplot"))
)
datass <- read.csv("C:/Users/yyu6/Documents/PR.csv", sep=",", stringsAsFactors = FALSE)
# Define server logic required to draw a histogram
server <- function(input, output) {
formulaText <- reactive({
input$DMS })
datasetInput <- reactive({
selection <- Input$DMS
subset(datass, DMS == selection)
})
output$caption <- renderText({formulaText()
})
ouptut$Trendplot <- renderPlot({
ggplot(datasetInput(), mapping = aes(x=DMS))+geom_histogram(stat = "count")
})
}
# Run the application
shinyApp(ui = ui, server = server)

Mouseover in plotly and shiny

I have some plotly code that perfectly calls the row names of a dataframe on mouseover both within RStudio and on RPubs . . . but not when embedded in Shiny.
The basic code is:
require(shiny)
require(plotly)
Trial <- read.table("http://history.emory.edu/RAVINA/Aozora/Data/Trial.txt", row.names = 1)
plot_ly(Trial, x=V1, y=V2, text=rownames(Trial), mode = "markers")
The Shiny version, however, is completely dead. What am I missing?
require(shiny)
require(plotly)
Trial <- read.table("http://history.emory.edu/RAVINA/Aozora/Data/Trial.txt", row.names = 1)
ui <- fluidPage(
titlePanel("Word Frequency Analysis for Meiji-era Authors"),
mainPanel(
plotOutput("plot"),
dataTableOutput("Print")
)
)
server <- function(input, output){
output$plot<-renderPlot({
p <- plot_ly(Trial, x=V1, y=V2, text=rownames(Trial), mode = "text")
plot(p)
})
output$Print<-renderDataTable({Trial})
}
shinyApp(ui = ui, server = server)
You need to swap out some base shiny functions for their plotly counterparts. Namely plotOutput -> plotlyOutput and renderPlot -> renderPlotly. Also, that last plot(p) isn't what you want to return: you just want to return p (the plot object).
require(shiny)
require(plotly)
Trial <- read.table("http://history.emory.edu/RAVINA/Aozora/Data/Trial.txt", row.names = 1)
ui <- fluidPage(
titlePanel("Word Frequency Analysis for Meiji-era Authors"),
mainPanel(
plotlyOutput("plot"),
dataTableOutput("Print")
)
)
server <- function(input, output){
output$plot<-renderPlotly({
p <- plot_ly(Trial, x=V1, y=V2, text=rownames(Trial), mode = "text")
#plot(p)
p
})
output$Print<-renderDataTable({Trial})
}
shinyApp(ui = ui, server = server)

Resources