Shiny app does not load properly - r

When I run my shiny app in RStudio, it works perfectly, here's the image:
propershiny
But when I upload it, it only displays the list of countries (in a very simple way without responsiveness) here's the link:https://alinapod.shinyapps.io/gendercomposition/ to check.
My code is:
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
selectInput(inputId = "ctry",
label = "Select countries:",
choices = levels(x$country),
selected = "Switzerland",
multiple = TRUE),
sliderInput(inputId = "year",
label = "Year:",
min = 1996, max = 2016,
value = 1996,
step = 1, animate = TRUE)
),
mainPanel(
plotOutput(outputId = "scatterplot", height = 600),
dataTableOutput(outputId = "datatable")
)
)
)
server <- function(input,output){
output$scatterplot <- renderPlot({
ggplot(data = filter(x, year == input$year & country %in% input$ctry),
aes_string(x = "female", y = "male", color = "region", size = "total_population")) +
geom_point() +
geom_text(data = filter(x, year == input$year & country %in% input$ctry),
aes(label = country), color = "black", size = 4.5, hjust = 0, vjust = -1.5) +
scale_color_manual("Regions", labels = c("AF" = "Africa", "ASIA" = "Asia", "AUS" = "Australia",
"EUR" = "Europe", "LATAM" = "Latin America",
"ME" = "Middle East", "NORAM" = "North America"),
values = c("AF" = "aquamarine3","ASIA" = "firebrick1", "AUS" = "darkorange2",
"EUR" = "dodgerblue3", "LATAM" = "forestgreen",
"ME" = "goldenrod1", "NORAM" = "dodgerblue4")) +
scale_size_continuous("",labels = NULL, breaks = NULL, range = c(2,15)) +
ggtitle("Gender Composition") +
xlab(paste("Female Percentage")) +
ylab(paste("Male")) +
scale_x_continuous(breaks = seq(0,80,10), limits = c(0,80)) +
scale_y_continuous(breaks = seq(0,80,10), limits = c(0,80))
})
output$datatable <- DT::renderDataTable({
req(input$ctry)
selected_countries <- select(filter(x, year == input$year & country %in% input$ctry),
country, female, male, total_population)
DT::datatable(data = selected_countries,
rownames = FALSE)
})
}
shinyApp(ui = ui, server = server)
And the same happens even when I upload the sample shiny app about geysers. No idea what is happening here.

Simply have your R script load the data explicitly and not rely on objects pre-loaded in global environment. No where is x used in renderPlot or renderDataTable assigned or uploaded by user. You can read data above the ui and server calls to avoid repeated assignment:
library(shiny)
library(DT)
library(dplyr)
library(ggplot2)
x <- read.csv('mydata.csv')
# x <- readRDS("mydata.rds")
ui <- ...
server <- ...
shinyApp(ui = ui, server = server)
And be sure to check off the data with the R script in pushing from RStudio to ShinyApps.io.

Related

Incorporating Shiny app sliders into ggplot graphs

I am trying to filter the dataframe that I use for my graph based on the input values from two sliders. I have sliders that select a range for temperature and wind speed in a given NFL game. (Each row of the dataframe is a quarterback's performance in a game along with game weather and QB measurables, so at least two rows per game.) How do I take the output from the sliders and filter the dataframe based on that? For example, how do I filter df$temperature based on the slider with id "z"?
library(shiny)
library(dplyr)
library(ggplot2)
library(tidyr)
df = read.csv("Combined_QB_Game_Data.csv")
df[df == "--"] = NA
df$Passes.Completed = as.double(df$Passes.Completed)
df$Passes.Attempted = as.double(df$Passes.Attempted)
df$Completion.Percentage = as.double(df$Completion.Percentage)
df$Passing.Yards = as.double(df$Passing.Yards)
df$Passing.Yards.Per.Attempt = as.double(df$Passing.Yards.Per.Attempt)
df$TD.Passes = as.double(df$TD.Passes)
df$Sacks = as.double(df$Sacks)
ui = fluidPage(
titlePanel("QB Performance"),
sidebarLayout(
sidebarPanel(
selectInput(inputId = "x",
label = "Options:",
choices = c("Ht", "Wt",
"Forty", "Vertical", "BenchReps",
"BroadJump", "Cone", "Shuttle", "Round", "Pick"),
selected = "Ht"),
selectInput(inputId = "y",
label = "Options2:",
choices = c("Passer.Rating","Passes.Completed","Passes.Attempted","Completion.Percentage","Passing.Yards","Passing.Yards.Per.Attempt","TD.Passes","Ints","Sacks"),
selected = "Passer.Rating"),
sliderInput("z", "Tempurature",
min = 0, max = 100, value = c(25, 75)),
sliderInput("a", "Wind",
min = 0, max = 30, value = c(5, 25))
),
mainPanel(
plotOutput(outputId = "scatterplot")
)
)
)
server = function(input, output) {
output$scatterplot = renderPlot({
p = ggplot(data = df) +
aes_string(x = input$x, y = input$y) +
geom_point()+
geom_smooth(method = "lm")
plot(p)
})
}
shinyApp(ui, server)
One possibility is to treat the data in a reactive conductor:
ggdata <- reactive({
bounds <- input$z
df %>% filter(temperature > bounds[1], temperature < bounds[2])
})
and then use it in the renderPlot:
output$scatterplot = renderPlot({
ggplot(data = ggdata()) +
aes_string(x = input$x, y = input$y) +
geom_point() +
geom_smooth(method = "lm")
})

In R/Shiny positioning ggplots chart in specifics places after select input choice

My main chart come from the select input and it is displayed at plotOutput('chart_1')
After this the country that was chosen on SelectInput is removed from the checkbox input and then the user should choose only 3 charts that will be placed at plotOutput('chart_2'),plotOutput('chart_3'),plotOutput('chart_4')
In other words: If I chose at selectInput 'Brazil' I will only have 5 options to include at positions plotOutput('chart_2'),plotOutput('chart_3'),plotOutput('chart_4'), and 'Brazil" will no longer be avaiable at checkbox input widgets.
My problem is that I am not be abl to set correctly thi idea with awesomeCheckboxGroupwidgets and include the other 3 charts tha the user will choose. This is what Ive done so far:
library(shiny)
library(ggplot2)
library(tidyverse)
library(gapminder)
library(shinyWidgets)
gapminder_df <-
gapminder %>% filter(country %in% c("Brazil", "Chile", "Argentina", "Peru")) %>%
group_split(country)
chart1 <-
ggplot(gapminder_df[[1]], aes(x = year, y = country)) + geom_line(color = 'red')
chart2 <-
ggplot(gapminder_df[[2]], aes(x = year, y = country)) + geom_line(color = 'green')
chart3 <-
ggplot(gapminder_df[[3]], aes(x = year, y = country)) + geom_line(color = 'blue')
chart4 <-
ggplot(gapminder_df[[4]], aes(x = year, y = country)) + geom_line(color = 'black')
chart5 <-
ggplot(gapminder_df[[4]], aes(x = year, y = country)) + geom_line(color = 'black')
chart6 <-
ggplot(gapminder_df[[4]], aes(x = year, y = country)) + geom_line(color = 'black')
all_countries <-
c("Brazil", "Chile", "Argentina", "Peru", "Uganda", "Turkey")
names(all_countries) <-
c("Brazil", "Chile", "Argentina", "Peru", "Uganda", "Turkey")
chart_list <-
list(chart1, chart2, chart3, chart4, chart5, chart6) %>% setNames(all_countries)
ui <- fluidPage(
selectInput(
inputId = 'country',
choices = all_countries,
label = "Paises"
),
awesomeCheckboxGroup(
inputId = "countries_check",
label = "Checkboxes",
choices = all_countries
),
div(
column(width = 6,
plotOutput('chart_1', height = '400px')),
column(
width = 6,
plotOutput('chart_2'),
plotOutput('chart_3'),
plotOutput('chart_4')
)
)
)
server <- function(input, output, session) {
output$chart_1 <- renderPlot({
chart_list[[input$country]]
})
# observeEvent(input$country,
#
# {
# if (input$country == input$countries_check) {
# awesomeCheckboxGroup(
# label = "Checkboxes",
# inputId = "countries_check",
# choices = input$country[-1]
# )
# }
output$chart_2 <- renderPlot({
chart_list[[input$countries_check[1]]]
})
output$chart_3 <- renderPlot({
chart_list[[input$countries_check[2]]]
})
output$chart_4 <- renderPlot({
chart_list[[input$countries_check[3]]]
})
# })
}
shinyApp(ui, server)
This could be achieved by updating your checkbox input using an observeEvent. To this end I set the choices to NULL in the UI then inside the observeEvent use updateAwesomeCheckboxGroup to update or set the available choices excluding the selected country:
library(shiny)
library(ggplot2)
library(tidyverse)
library(gapminder)
library(shinyWidgets)
ui <- fluidPage(
selectInput(
inputId = "country",
choices = all_countries,
label = "Paises"
),
awesomeCheckboxGroup(
inputId = "countries_check",
label = "Checkboxes",
choices = NULL
),
div(
column(
width = 6,
plotOutput("chart_1", height = "400px")
),
column(
width = 6,
plotOutput("chart_2"),
plotOutput("chart_3"),
plotOutput("chart_4")
)
)
)
server <- function(input, output, session) {
output$chart_1 <- renderPlot({
chart_list[[input$country]]
})
observeEvent(input$country, {
updateAwesomeCheckboxGroup(
session = session,
inputId = "countries_check",
choices = all_countries[!all_countries == input$country]
)
})
n_countries_checked <- reactive({
length(input$countries_check)
})
output$chart_2 <- renderPlot({
req(n_countries_checked() > 0)
chart_list[[input$countries_check[[1]]]]
})
output$chart_3 <- renderPlot({
req(n_countries_checked() > 1)
chart_list[[input$countries_check[[2]]]]
})
output$chart_4 <- renderPlot({
req(n_countries_checked() > 2)
chart_list[[input$countries_check[[3]]]]
})
}
shinyApp(ui, server)

How do I dynamically update a calculated value based on the number of input values in R Shiny?

I am trying to update the value in a plotly chart in R shiny whose calculated value depends on the number of inputs
library(shiny)
library(httr)
library(jsonlite)
library(dplyr)
library(plotly)
library(shinythemes)
library(flexdashboard)
library(shinydashboard)
setwd("X:/Work/Covid-19 Project/Shiny Dashboard")
rp_1 <- read.csv("Data/Risk Profile 1.csv")
rp_2 <- read.csv("Data/Risk Profile 2.csv")
gender <- c("Male","Female")
age <- c("Less than 20 years", "20 to 50 years","More than 50 years")
city <- c("Delhi","Chennai")
diabetes <- c("Have diabetes","Don't have diabetes")
hypertension <- c("Have hypertension","Don't have hypertension")
risk_level_est <- function(city, gender, age, db, ht){
p_inv <- as.numeric(rp_1 %>%
filter(City == city & Gender == gender) %>%
select(Prob))
p_adv <- as.numeric(rp_2 %>%
filter(Age == age & Diabetes == db & Hypertension == ht) %>%
summarise(Hosp + Death))
as.numeric(p_inv*p_adv*100)
}
sar_risk_level_est <- function(age, db, ht){
p_adv <- as.numeric(rp_2 %>%
filter(Age == age & Diabetes == db & Hypertension == ht) %>%
summarise(Hosp + Death))
as.numeric(0.2*p_adv*100)
}
about_page <- tabPanel(
title = "About",
titlePanel("About"),
"Created with R Shiny",
br(),
"2021 April"
)
main_page <- tabPanel(
title = "Estimator",
titlePanel(""),
sidebarLayout(
sidebarPanel(
title = "Inputs",
selectInput("gender", "Select your gender", gender),
selectInput("age", "Select your age", age),
selectInput("city", "Select your city", city),
selectInput("db", "Do you have diabetes", diabetes),
selectInput("ht", "Do you have hypertension", hypertension),
radioButtons("radio", "Do you want to include your household members",
choices = list("No" = 1,"Yes" = 2)),
conditionalPanel("input.radio == 2",
numericInput("members", label = "How many household members do you have?", value='1'),
uiOutput("member_input")
),
actionButton("risk","Calculate my risk profile")
),
mainPanel(
tabsetPanel(
tabPanel(
title = "Risk Profile",
plotlyOutput("risk_profile", height = 250, width = "75%"),
plotlyOutput("overall_risk_profile", height = 250, width = "75%")
)
)
)
)
)
ui <- navbarPage(
title = "Risk Estimator",
theme = shinytheme('united'),
main_page,
about_page
)
server <- function(input, output, session) {
output$member_input <- renderUI({
numMembers <- as.integer(input$members)
lapply(1:numMembers, function(i) {
list(tags$p(tags$u(h4(paste0("Member ", i)))),
selectInput(paste0("age", i), "Select their age", age, selected = NULL),
selectInput(paste0("db", i), "Do they have diabetes", diabetes, selected = NULL),
selectInput(paste0("ht", i), "Do they have hypertension", hypertension, selected = NULL))
})
})
risk_level <- eventReactive(input$risk, {
risk_level_est(input$city, input$gender, input$age, input$db, input$ht)
})
sar_risk_level <- eventReactive(input$risk,{
sar_risk <- 0
lapply(1:input$members, function(i){
sar_risk <- sar_risk + sar_risk_level_est(input[[paste0("age", i)]],input[[paste0("db", i)]],input[[paste0("ht", i)]])
})
as.numeric(sar_risk)
})
output$risk_profile <- renderPlotly({
fig <- plot_ly(
domain = list(x = c(0, 1), y = c(0, 1)),
value = risk_level(),
title = list(text = "Personal Risk Profile"),
type = "indicator",
mode = "gauge+number",
gauge = list(
axis = list(range = list(0, 15)),
bar = list(color = "gray"),
bgcolor = "white",
borderwidth = 2,
bordercolor = "gray",
steps = list(
list(range = c(0, 3.75), color = "darkgreen"),
list(range = c(3.75, 7.5), color = "chartreuse"),
list(range = c(7.5,11.25), color = "orange"),
list(range = c(11.25,15), color = "red")
)))
fig <- fig %>% layout(margin = list(l=30, r=30, t=80, b=30))
fig
})
output$overall_risk_profile <- renderPlotly({
fig <- plot_ly(
domain = list(x = c(0, 1), y = c(0, 1)),
value = risk_level() + sar_risk_level(),
title = list(text = "Overall Risk Profile"),
type = "indicator",
mode = "gauge+number",
gauge = list(
axis = list(range = list(0, 15+(25*input*members))),
bar = list(color = "gray"),
bgcolor = "white",
borderwidth = 2,
bordercolor = "gray",
steps = list(
list(range = c(0, 3.75), color = "darkgreen"),
list(range = c(3.75, 7.5), color = "chartreuse"),
list(range = c(7.5,11.25), color = "orange"),
list(range = c(11.25,15), color = "red")
)))
fig <- fig %>% layout(margin = list(l=30, r=30, t=80, b=30))
fig
})
}
shinyApp(ui, server)
While the risk_profile plot works fine, the overall_risk_profile plot throws the "non-numeric argument to binary operator" error. The sar_risk_level() value in overall_risk_profile is dependent on a calculation (sar_risk_level_est) which depends on the number of inputs. I want this value (sar_risk) to be initizialied to zero and updated everytime the action button is pressed.
Great looking app. I think it is just a typo. The code has 25*input*members instead of 25*input$members on line 151.

Why isn't my ggplot graph showing up on shiny?

Hello I'm doing this Shiny app for a class project and I was wondering why my graph isn't appearing at all. It runs without giving me an error and shows the side panels, but the graph is appearing blank. I've attached the code below. I've seen other posts on here that deal with us and I've tried them out, but nothing has been giving me the results I need. I just need this to show up by Tuesday, so I can present it on Thursday morning. Thank you!
#
# This is a Shiny web application. You can run the application by clicking
# the 'Run App' button above.
# Load Libraries
library(shiny)
library(tidyverse)
library(ggrepel)
library(dplyr)
library(magrittr)
library(quantmod)
# Load and Merge Data
wordbank = read_csv("/Users/Dohyun/Desktop/school stuff/year3/stat41/final project/administration_data.csv")
wordbank
# Define UI
ui <- fluidPage(
# Application title
titlePanel("Word Bank"),
# Sidebar layout with a input and output definitions
sidebarLayout(
# Inputs: Select variables to plot
sidebarPanel(
selectInput(inputId = "x",
label = "X-axis:",
choices = c("Age" = "age")),
selectInput(inputId = "y",
label = "Y-axis:",
choices = c("Word Size" = "comprehension")),
selectInput(inputId = 'language', 'Language: ',
choices = c("English (American)", "English (British)", "English (Australian)",
"American Sign Language","British Sign Language",
"Cantonese","Croatian","Czech", "Danish", "French (French)",
"French (Quebecois)", "German", "Greek (Cypriot)", "Hebrew",
"Italian", "Kigiriama", "Kiswahili", "Korean", "Latvian",
"Mandarin (Beijing)", "Mandarin (Taiwanese", "Norwegian",
"Portugeuse (European)", "Russian", "Slovak", "Spanish (European)",
"Spanish (Mexican)", "Swedish", "Turkish")),
sliderInput(inputId = "alpha",
label = "Alpha:",
min = 0, max = 1,
value = 0.5)
),
#Output
mainPanel(
plotOutput(outputId = "scatterplot"),
plotOutput(outputId = "boxplot"),
br(), # a little bit of visual separation
)
)
)
# Define server function --------------------------------------------
server <- function(input, output) {
lang_data <- reactive({
wordbank %>%
filter(language %in% input$language)
})
# Create scatterplot object the plotOutput function is expecting
output$lang_plot <- renderPlot({
# Creates base plot
p1 <-
ggplot(lang_data(), aes(x = input$x, y = input$y, fill = as.factor(age))) +
geom_boxplot(alpha = .6, outlier.shape = NA) +
geom_jitter(size = 0.2, alpha = input$alpha, width = 0.3, aes(color = as.factor(age))) +
scale_fill_viridis_d(end = .75, option = "D", guide=FALSE) +
scale_color_viridis_d(end = .75, option = "D", guide=FALSE) +
labs(x = str_to_title(str_replace_all(input$x, "_", " ")),
y = str_to_title(str_replace_all(input$y, "_", " "))) +
scale_x_continuous(breaks = seq(from = 16, to = 30, by = 2))
theme(panel.background = element_blank())
print(p1)
})
}
# Create the Shiny app object ---------------------------------------
shinyApp(ui, server)

How can I get both widgets in my shiny code to work simultaneously?

Currently, I am working on creating an interactive graph using shiny. My ui.R file contains two widgets, a checkbox and a selectInput:
checkboxGroupInput(inputId = "checkbox",
label = h3("Education Level"),
choices = c("Bachelor's Degree" = 'Bachelor',
"Master's Degree" = 'Master'
),
),
selectInput(inputId = "select",
label = h3("Gender"),
choices = c("Female" = 'F',
"Male" = 'M',
"Both" = 'B'
),
)
In my server.R file, I am able to get my selectInput to successfully run. However, my checkbox is currently not working. Here is an example:
server <- function(input, output) {
output$locksley_plot <- renderPlot({
choice_button <- input$select
check_box <- input$checkbox
BM <- ggplot(data = tech_salaries_bachelor) +
geom_point(
mapping = aes(x = Education, y = Male, color = "blue")
) +
scale_color_manual(labels = c("Men"), values=c("blue")) +
labs(
title = "Tech Salary Gender Comparison",
x = "Education Level",
y = "Salary ($)"
)
if(choice_button == 'M' && check_box == 'Bachelor') {
return(BM)
}
})
}
shinyServer(server)
#Locksley Here is an example shiny app that uses both widgets. I'm not entirely sure what outcome you are looking for, but thought this might be helpful.
tech_salaries_bachelor <- data.frame(
Education = c("Bachelor", "Bachelor", "Master", "Master", "Bachelor"),
Salary = c(30000, 35000, 55000, 50000, 27000),
Gender = c("F", "F", "F", "M", "M")
)
library(shiny)
library(tidyverse)
ui <- fluidPage(
checkboxGroupInput(inputId = "checkbox",
label = h3("Education Level"),
choices = c("Bachelor's Degree" = 'Bachelor',
"Master's Degree" = 'Master'
),
),
selectInput(inputId = "select",
label = h3("Gender"),
choices = c("Female" = 'F',
"Male" = 'M',
"Both" = 'B'
),
),
plotOutput("locksley_plot")
)
server <- function(input, output, session) {
my_data <- reactive({
req(input$checkbox)
tech_salaries_bachelor %>%
filter(Education %in% input$checkbox,
if(input$select != 'B') (Gender == input$select) else TRUE) %>%
group_by(Education, Gender) %>%
dplyr::summarise(Mean_Salary = mean(Salary))
})
output$locksley_plot <- renderPlot({
ggplot(data = my_data(), aes(x = Education, y = Mean_Salary, fill = Gender)) +
geom_bar(stat = "identity", position = position_dodge()) +
scale_fill_manual(labels = c("F" = "Female", "M" = "Male"), values=c("F" = "pink", "M" = "blue")) +
labs(
title = "Tech Salary Gender Comparison",
x = "Education Level",
y = "Average Salary ($)"
)
})
}
shinyApp(ui, server)

Resources