I'm trying to make a simple app with R using shiny that only has a highchart changing with the given parameter through slidebar.
I've looked through web, but there aren't any clear tutorial or simple example that I can compare my code with it.
So here's my code:
library(shiny)
library(highcharter)
library(dplyr)
sigene_all = read_csv("res/significant_genes.csv")
ui <- fluidPage(
titlePanel("Interactive Heatmap"),
sidebarLayout(
sidebarPanel(sliderInput(inputId = "slider", label = "Number of Cancers", min = 1, max = 12, value = 9)),
mainPanel(highchartOutput("heatmap"))
)
)
server <- function(input, output) {
output$heatmap <- renderChart({
hchart(sigene_all %>% filter(count >= input$slider),
type = "heatmap", hcaes(x = gene, y = cancer_type, value = sgnf), name = "sgnf") %>%
hc_add_theme(hc_theme_darkunica())
})
}
shinyApp(ui = ui, server = server)
and this is the error that I get when I run the app:
Warning: Error in server: could not find function "renderChart"
52: server [<..>/CTI/app.R#23]
Error in server(...) : could not find function "renderChart"
I've been searching but I haven't found anything related. I'd appreciate it if you help me with this simple code.
You need to use function renderHighchart() from the package highcharter to render your chart instead of renderChart(). Your code should look like this:
library(shiny)
library(highcharter)
library(dplyr)
sigene_all = read_csv("res/significant_genes.csv")
ui <- fluidPage(
titlePanel("Interactive Heatmap"),
sidebarLayout(
sidebarPanel(sliderInput(inputId = "slider", label = "Number of Cancers", min = 1, max = 12, value = 9)),
mainPanel(highchartOutput("heatmap"))
)
)
server <- function(input, output) {
output$heatmap <- renderHighchart({
hchart(sigene_all %>% filter(count >= input$slider),
type = "heatmap", hcaes(x = gene, y = cancer_type, value = sgnf), name = "sgnf") %>%
hc_add_theme(hc_theme_darkunica())
})
}
shinyApp(ui = ui, server = server)
Related
I am trying to use shiny controls to modify the data underlying a plotly chloropleth map.
Whenever I change the data the entire plot re-renders, which is quite slow. I'm guessing the bottleneck is redrawing the geojson polygons. Because the geojson never changes, I'm wondering if there is a way to keep the rendered widget intact but modify the z values only.
It looks like using plotlyProxy and plotlyProxyInvoke might be the right direction, but I can only see examples of an entire trace (which includes the geojson data) being replaced.
Sorry if I'm missing something or have been unclear - I have not used plotly very much, and even less so the js side of things.
See below for example code:
library(shiny)
library(dplyr)
library(plotly)
library(readr)
library(rjson)
zip_geojson <- fromJSON(file="https://raw.githubusercontent.com/hms1/testData/main/zip3_2.json")
plot_data <- read_csv(file="https://raw.githubusercontent.com/hms1/testData/main/plot_data.csv")
mapboxToken <- "pk.eyJ1IjoiaG1vcmdhbnN0ZXdhcnQiLCJhIjoiY2tmaTg5NDljMDBwbDMwcDd2OHV6cnd5dCJ9.8eLR4FtlO079Gq0NeSNoeg" #burner token
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
sliderInput("multip",
"n:",
min = 1,
max = 10,
value = 1)
),
mainPanel(
plotlyOutput("cPlot")
)
)
)
server <- function(input, output) {
output$cPlot <- renderPlotly({
plot_data_i <- plot_data%>%
mutate(log_count = case_when(log_count <= input$multip ~ log_count * input$multip,
TRUE ~ log_count))
plot_ly() %>%
add_trace(
type = "choroplethmapbox",
geojson = zip_geojson,
locations = plot_data_i$zip,
z = plot_data_i$log_count
) %>%
layout(
mapbox = list(
style = "light",
zoom = 3,
center = list(lon = -95.7129, lat = 37.0902)
)
) %>%
config(mapboxAccessToken = mapboxToken)
})
}
shinyApp(ui = ui, server = server)
For anyone else who comes across this post later, I found a solution.
It turns out that you can change data using the restyle method in plotlyProxyInvoke, as shown below.
library(shiny)
library(dplyr)
library(plotly)
library(readr)
library(rjson)
zip_geojson <- fromJSON(file="https://raw.githubusercontent.com/hms1/testData/main/zip3_2.json")
plot_data <- read_csv(file="https://raw.githubusercontent.com/hms1/testData/main/plot_data.csv")
mapboxToken <- "pk.eyJ1IjoiaG1vcmdhbnN0ZXdhcnQiLCJhIjoiY2tmaTg5NDljMDBwbDMwcDd2OHV6cnd5dCJ9.8eLR4FtlO079Gq0NeSNoeg"
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
sliderInput("multip",
"n:",
min = 1,
max = 10,
value = 1),
actionButton("Remove", "Remove Trace")
),
mainPanel(
plotlyOutput("cPlot")
)
)
)
server <- function(input, output, session) {
output$cPlot <- renderPlotly({
plot_ly(type = "choroplethmapbox", geojson = zip_geojson) %>%
layout(
mapbox = list(
style = "light",
zoom = 3,
center = list(lon = -95.7129, lat = 37.0902)
)
) %>%
config(mapboxAccessToken = mapboxToken)
})
plotproxy <- plotlyProxy("cPlot", session, deferUntilFlush = FALSE)
observeEvent(input$multip, {
plot_data_i <- plot_data %>%
mutate(log_count = case_when(log_count <= input$multip ~ log_count * input$multip,
TRUE ~ log_count))
plotproxy %>%
plotlyProxyInvoke("restyle", list(z = list(plot_data_i$log_count),
locations = list(plot_data_i$zip)))
})
}
shinyApp(ui = ui, server = server)
I'm trying to learn shiny on my own and it's been very fun so far. I'm trying to plot a singular point on a graph with both inputs coming from the user. I am getting a "Error in shinyApp(ui = ui, server = server) : object 'server' not found". Here's my code:
ui <- fluidPage(
titlePanel("Title"),
sidebarPanel(
sliderInput(inputId ="x1", 'I', min = 4, max = 12, value = 4),
sliderInput(inputId = "y1", 'Y', min = 0, max = 10, value = 1)),
plotOutput("Scale")
)
server() <- function(input, output){
output$Scale <- renderPlot({
ggplot(aes_string(x = input$x1, y = input$y1))+
geom_point() })
}
shinyApp(ui = ui, server = server)
Here is a complete working example, I hope this will help.
The slider inputs will provide numerical information for your plot. This might be easier to conceptualize if placed in a data frame (see below).
The aes aesthetic mapping provides information on x and y axis for your plot, and uses data to indicate dataset to use for plot.
Finally, added limits to appreciate the point moving around the graph with slider changes (otherwise, the axis will automatically rescale).
Lots more you can learn on ggplot2 here:
https://ggplot2.tidyverse.org/
library(ggplot2)
library(shiny)
ui <- fluidPage(
titlePanel("Title"),
sidebarPanel(
sliderInput(inputId ="x1", 'I', min = 4, max = 12, value = 4),
sliderInput(inputId = "y1", 'Y', min = 0, max = 10, value = 1)),
plotOutput("Scale")
)
server <- function(input, output){
output$Scale <- renderPlot({
my_data <- data.frame(x = input$x1, y = input$y1)
ggplot(aes(x = x, y = y), data = my_data)+
geom_point() +
xlim(4, 12) +
ylim(0, 10)
})
}
shinyApp(ui = ui, server = server)
Am learning to use R shiny and I am trying to create a heatmap that allows the user to specify the height in plotlyOutput to prevent labels from being clumped together. My minimal working code:
library(shiny)
library(plotly)
ui <- fluidPage(
titlePanel("Heatmap"),
sidebarLayout(
sidebarPanel(
sliderInput("mapHeight",
"Heatmap Height",
min = 500,
max = 1000,
value =500),
sliderInput("L", "left adjust", min = 0, max =900, value = 80)
),
mainPanel(plotlyOutput("heatmap"))
)
)
server <- function(input, output) {
output$heatmap <- renderPlotly({
p<- heatmaply(mtcars, plot_method = "plotly")%>%
layout(margin = list(l = input$L, r =50 , t=0, b=90))
#not sure why this is being ignored
ggplotly(p, height = input$mapHeight)
})
}
shinyApp(ui = ui, server = server)
The constraint is related to the heatmaply package, the solution below is temporary while plotly continues to accept the height argument in layout.
Warning: Specifying width/height in layout() is now deprecated.
Please specify in ggplotly() or plot_ly()
You could approach the developer on their GitHub and raise and issue or better yet a pull request with the changes you propose. For the time being, the solution below works with Plotly 4.7.1.
app.R
library(shiny)
library(heatmaply)
ui <- fluidPage(
titlePanel("Heatmap"),
sidebarLayout(
sidebarPanel(
sliderInput("mapHeight", "Heatmap Height",
min = 500, max = 1000, value = 500),
sliderInput("L", "left adjust", min = 0, max = 900, value = 80)
),
mainPanel(plotlyOutput("heatmap"))
)
)
server <- function(input, output) {
output$heatmap <- renderPlotly({
heatmaply(mtcars) %>%
layout(margin = list(l = input$L, r = 50, t = 0, b = 90),
height = input$mapHeight)
})
}
shinyApp(ui = ui, server = server)
The below shiny app fails to render the Network graph. Whereas with an Rmd file I do get the graphic. Below an reproducible example. Keen to know where the error is if any.
library(shiny)
library(shinythemes)
library(networkD3)
library(data.tree)
library(tidyr)
# Define UI for application that draws a network graph
ui <- fluidPage(theme = shinytheme("slate"),
sliderInput("number",
"Random Numbers:",
min = 1,
max = 100,
value = 20),
# Show a plot of the generated distribution
radialNetworkOutput("radial")
)
# Define server logic required to draw a network graph
server <- function(input, output) {
Data_tree <- reactive({
data.frame(Start="Class",
Asset = sample(c("FI","Equity","Currency"),input$number,replace = TRUE),
Sub_Asset = sample(c("Asia","Europe","USA"),input$number,replace = TRUE),
Ticker = replicate(input$number,paste0(sample(LETTERS,3),collapse=""))) %>%
unite(col="pathString",Start,Asset,Sub_Asset,Ticker,sep="-",remove=FALSE) %>%
select(-Start) %>% as.Node(pathDelimiter = "-")
})
output$radial <- renderRadialNetwork({
# draw the radialNetwork with the specified size
ToListExplicit(Data_tree(), unname = TRUE )
})
}
# Run the application
shinyApp(ui = ui, server = server)
The graphic should look like below:
Just discovered the short coming in the code. Within the renderRadialNetwork function needed to add radialNetwork()
Here is the working final code.
library(shiny)
library(shinythemes)
library(networkD3)
library(data.tree)
library(tidyr)
# Define UI for application that draws a network graph
ui <- fluidPage(theme = shinytheme("slate"),
sliderInput("number",
"Random Numbers:",
min = 1,
max = 100,
value = 20),
# Show a plot of the generated distribution
radialNetworkOutput("radial")
)
# Define server logic required to draw a network graph
server <- function(input, output) {
Data_tree <- reactive({
data.frame(Start="Class",
Asset = sample(c("FI","Equity","Currency"),input$number,replace = TRUE),
Sub_Asset = sample(c("Asia","Europe","USA"),input$number,replace = TRUE),
Ticker = replicate(input$number,paste0(sample(LETTERS,3),collapse=""))) %>%
unite(col="pathString",Start,Asset,Sub_Asset,Ticker,sep="-",remove=FALSE) %>%
select(-Start) %>% as.Node(pathDelimiter = "-")
})
output$radial <- renderRadialNetwork({
# draw the radialNetwork with the specified size
radialNetwork(ToListExplicit(Data_tree(), unname = TRUE ), linkColour = "#ccc",nodeColour = "#fff",
nodeStroke = "orange",textColour = "#cccccc")
})
}
# Run the application
shinyApp(ui = ui, server = server)
I need to be able to add another trace to a plot after a mouse click. I am using R's web framework Shiny to display the plot in a web browser. The series I want to add is dots or any series at this point.
I need to draw lines on the plot also. I want to click a starting point and a ending and a line pass through the clicked points.
This is what I have so far.
#############To Update
#if (!require("devtools"))
#install.packages("devtools")
#devtools::install_github("jbkunst/highcharter")
library("shiny")
library("highcharter")
dots<-hc_add_series_scatter(cars$speed, cars$dist)
hc_base <- highchart() %>%
hc_xAxis(categories = citytemp$month) %>%
hc_add_series(name = "Tokyo", data = citytemp$tokyo)
ui <- fluidPage(
h2("Viewer"),
fluidRow(
h3(""), highchartOutput("hc_1", width = "100%", height = "800px"),
h3("Click"), verbatimTextOutput("hc_1_input2")
)
)
server = function(input, output) {
output$hc_1 <- renderHighchart({
hc_base %>%
hc_add_theme(hc_theme_ffx())%>%
hc_tooltip(backgroundColor="skyblue",crosshairs = TRUE, borderWidth = 5, valueDecimals=2)%>%
hc_add_event_series(series="dots", event = "click")
})
output$hc_1_input2 <- renderPrint({input$hc_1_click })
}
shinyApp(ui = ui, server = server)
Any help would be greatly appreciated.
This could be one way of doing it:
library(shiny)
library(highcharter)
hc_base <- highchart() %>%
hc_xAxis(categories = citytemp$month) %>%
hc_add_series(name = "Tokyo", data = citytemp$tokyo)
ui <- fluidPage(
h2("Viewer"),
fluidRow(
h3(""), highchartOutput("hc_1", width = "100%", height = "800px"),
h3("Click"), verbatimTextOutput("hc_1_input2")
)
)
server = function(input, output) {
output$hc_1 <- renderHighchart({
hc_base %>%
hc_add_theme(hc_theme_ffx())%>%
hc_tooltip(backgroundColor="skyblue",crosshairs = TRUE, borderWidth = 5, valueDecimals=2)%>%
hc_add_event_point(event = "click")
})
observeEvent(input$hc_1_click,{
output$hc_1 <- renderHighchart({
hc_base %>%
hc_add_theme(hc_theme_ffx())%>%
hc_tooltip(backgroundColor="skyblue",crosshairs = TRUE, borderWidth = 5, valueDecimals=2)%>%
hc_add_series_scatter(cars$speed, cars$dist)
})
})
output$hc_1_input2 <- renderPrint({input$hc_1_click })
}
shinyApp(ui = ui, server = server)
Hope it helps!