I'd like to use check box input to allow to show different island levels (within the categorical variable selected for the x-axis) with separate boxplots and different colors with a legend. But if this check box is not selected, I just want to show boxplot without fill=legend that is:
ggplot(dat(), aes_string(x = isolate(input$xaxis), y = input$yaxis)) +
geom_boxplot()
This R code is what I tried to use but It didn't work. Could you please help me to solve or tell me what makes error with my R code?
Thank you in advance
library(shiny)
library(palmerpenguins)
library(ggplot2)
library(dplyr)
penguin <- penguins
penguin$year <- as.factor(penguin$year)
ui <- fluidPage(
titlePanel("Data Visualisation of Penguins Data"),
sidebarPanel(
selectInput("yaxis",
label = "Choose a y-axis variable to display",
choices = list("bill_length_mm",
"bill_depth_mm",
"flipper_length_mm",
"body_mass_g"),
selected = "bill_length_mm"),
selectInput("xaxis",
label = "Choose a x-axis variable to display",
choices = c("species",
"sex",
"year"),
selected = "sex"),
checkboxGroupInput("islandlevels",
label = "Check to display different island levels",
choices = c("island"),
selected = NULL),
br(), br(),
selectInput("species",
label = "Choose species to view separate plot",
choices = list("Adelie",
"Chinstrap",
"Gentoo"),
selected = NULL)),
mainPanel(
plotOutput("plot1"),
br(), br(),
plotOutput("plot2")
)
)
server <- function(input, output){
dat <- reactive({
if(input$xaxis == "sex") penguin[!is.na(penguin$sex),] else penguin
})
output$plot1 <- renderPlot({
if(input$islandlevels == "island") {
req(penguin, input$xaxis, input$yaxis)
ggplot(dat(), aes_string(x = isolate(input$xaxis), y = input$yaxis, fill=island)) +
geom_boxplot()
}
if(input$islandlevels = NULL) {
req(penguin, input$xaxis, input$yaxis)
ggplot(dat(), aes_string(x = isolate(input$xaxis), y = input$yaxis)) +
geom_boxplot()}
})
}
shinyApp(ui = ui, server = server)
As long as you don't want any other checkbox inputs you could use a checkboxInput instead of a checkboxGroupInput which makes checking a bit easier.
One issue in your server was that you used island instead of "island". Additionally you can simplify your code a little bit by using fill <- if (input$islandlevels) "island" which will return NULL is the the checkbox was not checked and "island" otherwise. This way you can handle both case with only one ggplot statement .
The full reproducible code:
library(shiny)
library(palmerpenguins)
library(ggplot2)
library(dplyr)
penguin <- penguins
penguin$year <- as.factor(penguin$year)
ui <- fluidPage(
titlePanel("Data Visualisation of Penguins Data"),
sidebarPanel(
selectInput("yaxis",
label = "Choose a y-axis variable to display",
choices = list("bill_length_mm",
"bill_depth_mm",
"flipper_length_mm",
"body_mass_g"),
selected = "bill_length_mm"),
selectInput("xaxis",
label = "Choose a x-axis variable to display",
choices = c("species",
"sex",
"year"),
selected = "sex"),
checkboxInput("islandlevels",
label = "Check to display different island levels",
value = FALSE),
br(), br(),
selectInput("species",
label = "Choose species to view separate plot",
choices = list("Adelie",
"Chinstrap",
"Gentoo"),
selected = NULL)),
mainPanel(
plotOutput("plot1"),
br(), br(),
plotOutput("plot2")
)
)
server <- function(input, output){
dat <- reactive({
if(input$xaxis == "sex") penguin[!is.na(penguin$sex),] else penguin
})
output$plot1 <- renderPlot({
req(penguin, input$xaxis, input$yaxis)
fill <- if (input$islandlevels) "island"
ggplot(dat(), aes_string(x = isolate(input$xaxis), y = input$yaxis, fill = fill)) +
geom_boxplot()
})
}
shinyApp(ui = ui, server = server)
Related
I should create in my shiny app this conditions:
In the UI setup add a selectInput field: the first argument is
the name (how to access the selection in the server setup, we will
call this "species"), the second argument is the label (appears on
the app), and the third argument should list the choices: here we
want to choose between the three different species (can you
obtain the three choices from the data directly?).
I receive this error in my code:
I receive this error:
Error in match.arg(position) : 'arg' must be NULL or a character vector
CODE:
library(shiny)
library(palmerpenguins)
library(ggplot2)
# Define UI for application that draws a plot
ui <- fluidPage(
# Application title
titlePanel("Penguins"),
# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(
selectInput(inputId = "VarX",
label = "Select X-axis Variable",
choices = list("flipper_length_mm","species","island",
"bill_length_mm","bill_depth_mm","body_mass_g",
"sex","year")),
selectInput(inputId = "VarY",
label = "Select Y-axis Variable",
choices = list("flipper_length_mm","species","island",
"bill_length_mm","bill_depth_mm","body_mass_g",
"sex","year")),
selectInput(
inputId = "varColor",
label = "Color",
choices = c("species"),
selected = "species")),
selectInput(
inputId = "species",
label = "select species",
choices = list("adelie","gentoo","chinstrap")),
# Show a plot
mainPanel(
plotOutput("scatter")
)
)
)
#Define server logic required to draw a scatter
server <- function(input, output) {
pengu <- reactive({ggplot(penguins,
aes(y = bill_depth_mm, x = bill_length_mm))+
geom_point(aes(color = .data[[input$species]]))})
output$scatter <- renderPlot({
pengu()
})
}
# Run the application
shinyApp(ui = ui, server = server)
I have plotted scatterplot for each country, and I am trying to add a correlation coefficient under the scatterplot, but I keep getting errors saying "Selections can't have missing values." even after using na.rm
Can someone help me with this??
I appreciate any help you can provide.
data link EuropeIndia
#
# This is a Shiny web application. You can run the application by clicking
# the 'Run App' button above.
#
# Find out more about building applications with Shiny here:
#
# http://shiny.rstudio.com/
#
library(shiny)
library(plotly)
library(DT)
library(tidyverse)
library(car)
library(ggpubr)
covid <- read.csv("EuropeIndia.csv")
title <- tags$a(href='https://ourworldindata.org/covid-vaccinations?country=OWID_WRL',
'COVID 19 Vaccinations')
# Define UI for application
ui <- fluidPage(
headerPanel(title = title),
# Application title
titlePanel("COVID vaccinations: Deaths Vs All variables"),
# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(
selectInput("location", "1. Select a country",
choices = covid$location, selectize = TRUE, multiple = FALSE),
br(),
helpText("2. Select variables for scatterplot"),
selectInput(inputId = "y", label = "Y-axis:",
choices = c("total_deaths", "new_deaths"),
selected = "Deaths",),
br(),
selectInput(inputId = "x", label = "X-axis:",
choices = names(subset(covid,select = -c(total_deaths,new_deaths,
iso_code, continent,date,location), na.rm =TRUE)),
selectize = TRUE,
selected = "Comparator variables")
),
mainPanel(
textOutput("location"),
#plotOutput("Scatterplot"),
tabsetPanel(
type = "tabs",
tabPanel("Scatterplot", plotlyOutput("scatterplot"),
verbatimTextOutput("correlation"),
verbatimTextOutput("interpretation")),
tabPanel("Summary of COVID data", verbatimTextOutput("summary")),
tabPanel("Dataset", DTOutput("dataset")))
)
)
)
# Define server logic
server <- function(input, output) {
output$location <- renderPrint({locationfilter <- subset(covid, covid$location == input$location)})
output$summary <- renderPrint({summary(covid)})
output$dataset <- renderDT(
covid, options = list(
pageLength = 50,
initComplete = JS('function(setting, json) { alert("done"); }')
)
)
output$scatterplot <- renderPlotly({
ggplotly(
ggplot(subset(covid, covid$location == input$location),
aes(y = .data[[input$y]], x = .data[[input$x]],col = factor(stringency_index)))+
geom_smooth()+geom_point()+labs(col ="Stringency Index")
)
})
output$correlation <- renderText({
x= subset(covid, covid$location == input$location) %>% dplyr::select(as.numeric(!!!input$x, na.rm =TRUE))
y= subset(covid, covid$location == input$location) %>% dplyr::select(as.numeric(!!!input$y, na.rm = TRUE))
var(x,y, na.rm = T, use)
cor(x,y, method = 'pearson', na.rm =T)
})
}
# Run the application
shinyApp(ui = ui, server = server)
First of all you should select just one Country from the selection list.
For error checking I propose you the next code.
library(shiny)
library(plotly)
library(DT)
library(tidyverse)
library(car)
library(ggpubr)
covid <- read.csv("EuropeIndia.csv")
title <- tags$a(href='https://ourworldindata.org/covid-vaccinations?country=OWID_WRL',
'COVID 19 Vaccinations')
# Define UI for application
ui <- fluidPage(
headerPanel(title = title),
# Application title
titlePanel("COVID vaccinations: Deaths Vs All variables"),
# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(
selectInput("location", "1. Select a country",
choices = covid$location[1], selectize = TRUE, multiple = FALSE),
br(),
helpText("2. Select variables for scatterplot"),
selectInput(inputId = "y", label = "Y-axis:",
choices = c("total_deaths", "new_deaths"),
selected = "Deaths",),
br(),
selectInput(inputId = "x", label = "X-axis:",
choices = names(subset(covid,select = -c(total_deaths,new_deaths,
iso_code, continent,date,location), na.rm =TRUE)),
selectize = TRUE,
selected = "Comparator variables")
),
mainPanel(
textOutput("location"),
#plotOutput("Scatterplot"),
tabsetPanel(
type = "tabs",
tabPanel("Scatterplot", plotlyOutput("scatterplot"),
verbatimTextOutput("correlation"),
verbatimTextOutput("interpretation")),
tabPanel("Summary of COVID data", verbatimTextOutput("summary")),
tabPanel("Dataset", DTOutput("dataset")))
)
)
)
# Define server logic
server <- function(input, output) {
output$location <- renderPrint({locationfilter <- subset(covid, covid$location == input$location)})
output$summary <- renderPrint({summary(covid)})
output$dataset <- renderDT(
covid, options = list(
pageLength = 50,
initComplete = JS('function(setting, json) { alert("done"); }')
)
)
output$scatterplot <- renderPlotly({
ggplotly(
ggplot(subset(covid, covid$location == input$location),
aes(y = .data[[input$y]], x = .data[[input$x]],col = factor(stringency_index)))+
geom_smooth()+geom_point()+labs(col ="Stringency Index")
)
})
output$correlation <- renderText({
x <- covid[covid$location == input$location, input$x]
y <- covid[covid$location == input$location, input$y]
xy = data.frame(x,y)
xy = xy[complete.cases(xy),]
var(xy)
cor(xy,method = 'pearson')
})
}
# Run the application
shinyApp(ui = ui, server = server)
I am creating a Shiny app and I have started using the Waiter package.
When I load the app, before doing anything, we cannot see anything (at it is expected). When I generate the plot, the loading bar appears but when it finishes, it doesn't disappear. It stays a white box that it still can be seen.
Loading....
It has finished.
Does anyone know how to remove it?
Thanks in advance!
Code:
library(shiny)
library(magrittr)
library(DT)
library(ggplot2)
library(waiter)
new_choices <- setNames(names(mtcars), names(mtcars))
ui <- fluidPage(
# Application title
titlePanel("My shiny app"),
sidebarLayout(
sidebarPanel(
tabsetPanel(
tabPanel("Selection",
selectInput("x_axis", "Choose x axis",
choices = new_choices),
selectInput("y_axis", "Choose y axis",
choices = new_choices),
hr(),
),
tabPanel("Titles",
hr(),
textInput(inputId = "title", "You can write the title:", value = "This is the title"),
textInput(inputId = "xlab", "You can re-name the x-axis:", value = "x-axis...."),
textInput(inputId = "ylab", "You can re-name the y-axis:", value = "y-axis ...."),
),
tabPanel("Calculations",
hr(),
checkboxInput("log2", "Do the log2 transformation", value = F),
checkboxInput("sqrt", "Calculate the square root", value = F),
)
),
useWaitress(),
actionButton(inputId = "drawplot", label = "Show the plot")
),
# Show a plot of the generated distribution
mainPanel(
plotOutput("plot"),
)
)
)
server <- function(input, output, session) {
waitress <- Waitress$new(theme = "overlay-percent", min = 0, max = 10)
data <- reactive({
mtcars
})
filtered_data <- reactive({
data <- data()
if(input$log2 == TRUE){
data <- log2(data+1)
}
if(input$sqrt == TRUE){
data <- sqrt(data)
}
return(data)
})
v <- reactiveValues()
observeEvent(input$drawplot, {
# use notification
waitress$notify()
for(i in 1:10){
waitress$inc(1) # increase by 10%
Sys.sleep(.3)
}
v$plot <- ggplot() +
geom_point(data = filtered_data(),
aes_string(x = input$x_axis, y = input$y_axis)) +
xlab(input$xlab) +
ylab(input$ylab) +
ggtitle(input$title)
waitress$close() # hide when done
})
output$plot <- renderPlot({
if (is.null(v$plot)) return()
v$plot
})
}
shinyApp(ui, server)
Feels like a bug to me. You may file an issue to the waiter github repository and ask them to fix it. Meanwhile, a workaround we can do is to manually show and hide the bar by ourselves.
library(shiny)
library(magrittr)
library(DT)
library(ggplot2)
library(waiter)
library(shinyjs)
new_choices <- setNames(names(mtcars), names(mtcars))
ui <- fluidPage(
# Application title
titlePanel("My shiny app"),
sidebarLayout(
sidebarPanel(
tabsetPanel(
tabPanel("Selection",
selectInput("x_axis", "Choose x axis",
choices = new_choices),
selectInput("y_axis", "Choose y axis",
choices = new_choices),
hr(),
),
tabPanel("Titles",
hr(),
textInput(inputId = "title", "You can write the title:", value = "This is the title"),
textInput(inputId = "xlab", "You can re-name the x-axis:", value = "x-axis...."),
textInput(inputId = "ylab", "You can re-name the y-axis:", value = "y-axis ...."),
),
tabPanel("Calculations",
hr(),
checkboxInput("log2", "Do the log2 transformation", value = F),
checkboxInput("sqrt", "Calculate the square root", value = F),
)
),
useWaitress(),
useShinyjs(),
actionButton(inputId = "drawplot", label = "Show the plot")
),
# Show a plot of the generated distribution
mainPanel(
plotOutput("plot")
)
)
)
server <- function(input, output, session) {
waitress <- Waitress$new(theme = "overlay-percent", min = 0, max = 10)
data <- reactive({
mtcars
})
filtered_data <- reactive({
data <- data()
if(input$log2 == TRUE){
data <- log2(data+1)
}
if(input$sqrt == TRUE){
data <- sqrt(data)
}
return(data)
})
v <- reactiveValues()
observeEvent(input$drawplot, {
# use notification
show(selector = '.waitress-notification.notifications')
waitress$notify()
for(i in 1:10){
waitress$inc(1) # increase by 10%
Sys.sleep(.3)
}
v$plot <- ggplot() +
geom_point(data = filtered_data(),
aes_string(x = input$x_axis, y = input$y_axis)) +
xlab(input$xlab) +
ylab(input$ylab) +
ggtitle(input$title)
waitress$close()
hide(selector = '.waitress-notification.notifications')
})
output$plot <- renderPlot({
if (is.null(v$plot)) return()
v$plot
})
}
shinyApp(ui, server)
I am creating a shiny app with some tabs and I am using the shinycssloaders package in order to show a spinner AFTER pressing the actionButton. I saw this post because I was having the same problem... I followed the solution that it was given to the post, but as I my app is different (it has tabPanels, it doesn't work properly, the spinner still apears).
For example, if you click on "Show the plot" in the first tab (selection) and then you want to want to do the log2 transformation o calculate the square root (3rd tab, calculations), before clicking the actionButton the spinner appears and the plot updates. It happens the same when you want to change the titles (2nd tab).
Does anyone know how to fix it?
Thanks very much in advance
The code:
library(shiny)
library(magrittr)
library(DT)
library(ggplot2)
library(shinycssloaders)
new_choices <- setNames(names(mtcars), names(mtcars))
ui <- fluidPage(
# Application title
titlePanel("My shiny app"),
sidebarLayout(
sidebarPanel(
tabsetPanel(
tabPanel("Selection",
selectInput("x_axis", "Choose x axis",
choices = new_choices),
selectInput("y_axis", "Choose y axis",
choices = new_choices),
hr(),
),
tabPanel("Titles",
hr(),
textInput(inputId = "title", "You can write the title:", value = "This is the title"),
textInput(inputId = "xlab", "You can re-name the x-axis:", value = "x-axis...."),
textInput(inputId = "ylab", "You can re-name the y-axis:", value = "y-axis ...."),
),
tabPanel("Calculations",
hr(),
checkboxInput("log2", "Do the log2 transformation", value = F),
checkboxInput("sqrt", "Calculate the square root", value = F),
)
),
actionButton(inputId = "drawplot", label = "Show the plot")
),
# Show a plot of the generated distribution
mainPanel(
# plotOutput("plot")
uiOutput("spinner"),
)
)
)
server <- function(input, output, session) {
data <- reactive({
mtcars
})
filtered_data <- reactive({
data <- data()
if(input$log2 == TRUE){
data <- log2(data+1)
}
if(input$sqrt == TRUE){
data <- sqrt(data)
}
return(data)
})
observeEvent(input$drawplot, {
output$spinner <- renderUI({
withSpinner(plotOutput("plot"), color="black")
})
output$plot <- renderPlot({
Sys.sleep(3)
ggplot() +
geom_point(data = filtered_data(),
aes_string(x = input$x_axis, y = input$y_axis)) +
xlab(input$xlab) +
ylab(input$ylab) +
ggtitle(input$title)
})
})
}
shinyApp(ui, server)
Is it OK like this? I'm not sure to understand all your requirements. To avoid the spinner at the start-up, I use a conditionalPanel. In the server code, I did some changes. It is not recommended to define some output inside an observer.
library(shiny)
library(magrittr)
library(ggplot2)
library(shinycssloaders)
new_choices <- setNames(names(mtcars), names(mtcars))
ui <- fluidPage(
# Application title
titlePanel("My shiny app"),
sidebarLayout(
sidebarPanel(
tabsetPanel(
tabPanel(
"Selection",
selectInput("x_axis", "Choose x axis",
choices = new_choices),
selectInput("y_axis", "Choose y axis",
choices = new_choices),
hr(),
),
tabPanel(
"Titles",
hr(),
textInput(inputId = "title", "You can write the title:", value = "This is the title"),
textInput(inputId = "xlab", "You can re-name the x-axis:", value = "x-axis...."),
textInput(inputId = "ylab", "You can re-name the y-axis:", value = "y-axis ...."),
),
tabPanel(
"Calculations",
hr(),
checkboxInput("log2", "Do the log2 transformation", value = F),
checkboxInput("sqrt", "Calculate the square root", value = F),
)
),
actionButton(inputId = "drawplot", label = "Show the plot")
),
# Show a plot of the generated distribution
mainPanel(
conditionalPanel(
condition = "input.drawplot > 0",
style = "display: none;",
withSpinner(plotOutput("plot"))
)
)
)
)
server <- function(input, output, session) {
data <- reactive({
mtcars
})
filtered_data <- reactive({
data <- data()
if(input$log2 == TRUE){
data <- log2(data+1)
}
if(input$sqrt == TRUE){
data <- sqrt(data)
}
return(data)
})
gg <- reactive({
ggplot() +
geom_point(data = filtered_data(),
aes_string(x = input$x_axis, y = input$y_axis)) +
xlab(input$xlab) +
ylab(input$ylab) +
ggtitle(input$title)
}) %>%
bindEvent(input$drawplot)
output$plot <- renderPlot({
Sys.sleep(3)
gg()
})
}
shinyApp(ui, server)
You need to isolate the expressions that you don't want to trigger the rendering event inside renderPlot
library(shiny)
library(magrittr)
library(DT)
library(ggplot2)
library(shinycssloaders)
new_choices <- setNames(names(mtcars), names(mtcars))
ui <- fluidPage(
# Application title
titlePanel("My shiny app"),
sidebarLayout(
sidebarPanel(
tabsetPanel(
tabPanel("Selection",
selectInput("x_axis", "Choose x axis",
choices = new_choices),
selectInput("y_axis", "Choose y axis",
choices = new_choices),
hr(),
),
tabPanel("Titles",
hr(),
textInput(inputId = "title", "You can write the title:", value = "This is the title"),
textInput(inputId = "xlab", "You can re-name the x-axis:", value = "x-axis...."),
textInput(inputId = "ylab", "You can re-name the y-axis:", value = "y-axis ...."),
),
tabPanel("Calculations",
hr(),
checkboxInput("log2", "Do the log2 transformation", value = F),
checkboxInput("sqrt", "Calculate the square root", value = F),
)
),
actionButton(inputId = "drawplot", label = "Show the plot")
),
# Show a plot of the generated distribution
mainPanel(
# plotOutput("plot")
uiOutput("spinner"),
)
)
)
server <- function(input, output, session) {
data <- reactive({
mtcars
})
filtered_data <- reactive({
data <- data()
if(input$log2 == TRUE){
data <- log2(data+1)
}
if(input$sqrt == TRUE){
data <- sqrt(data)
}
return(data)
})
observeEvent(input$drawplot, {
output$spinner <- renderUI({
withSpinner(plotOutput("plot"), color="black")
})
output$plot <- renderPlot({
Sys.sleep(3)
ggplot() +
geom_point(data = isolate(filtered_data()),
aes_string(x = isolate(input$x_axis), y = isolate(input$y_axis))) +
xlab(isolate(input$xlab)) +
ylab(isolate(input$ylab)) +
ggtitle(isolate(input$title))
})
})
}
shinyApp(ui, server)
Read more about shiny reactivity and isolation: https://shiny.rstudio.com/articles/isolation.html
I am new to working with shiny package. I am trying to use it to display a ggplot2 graph. I get no errors with my code, however data points are not appearing on the graph. When I select the variables from ui, the axes labels changes accordingly but the data is not added to the plot.
Thank you,
Code:
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
selectInput(inputId = "y",
label = "Y-axis:",
choices = c("P-value", "P-adjust"),
selected = "P-adjust"),
selectInput(inputId = "x" ,
label = "X-axis:",
choices = c("FC", "Mean_Count_PD"),
selected = "FC")
),
mainPanel(plotOutput(outputId = "scatterplot"))
))
server <- function(input, output)
{
output$scatterplot <- renderPlot({
ggplot(data = mir, aes(input$x,input$y)) + geom_point()
})
}
The issue is that you have to tell ggplot that your inputs are names of variables in your dataset. This could be achieved e.g. by making use of the .data pronoun, i.e. instead of using input$x which is simply a string use .data[[input$x]] which tells ggplot that by input$x you mean the variable with that name in your data:
As you provided no data I could not check but this should give you the desired result:
library(shiny)
library(ggplot2)
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
selectInput(inputId = "y",
label = "Y-axis:",
choices = c("P-value", "P-adjust"),
selected = "P-adjust"),
selectInput(inputId = "x" ,
label = "X-axis:",
choices = c("FC", "Mean_Count_PD"),
selected = "FC")
),
mainPanel(plotOutput(outputId = "scatterplot"))
))
server <- function(input, output) {
output$scatterplot <- renderPlot({
ggplot(data = mir, aes(.data[[input$x]], .data[[input$y]])) + geom_point()
})
}
shinyApp(ui, server)