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

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)

Related

Shiny R: Can't display plot

I try to display interactive plots by using R shiny. I can successfully make the GUI and published, but the plots in tabPanel shows nothing, just like the picture shows below. There is the data I used (have been downloaded into my laptop).
I think problem may caused by the way how I preprocessing my data in server.R, but whatever I tried, it still display nothing. No Error shows when I run the app.
enter image description here
My code in ui.R:
library(shiny)
shinyUI(fluidPage(
titlePanel("Data Viz Lab"),
sidebarLayout(
sidebarPanel(
## Add X-Variable select element
selectInput(inputId = "var_x",
label = h5("X-Variable"),
choices = c("Structure.Cost", "Land.Value", "Home.Value", "Home.Price.index"),
selected = "Land.Value"),
## Add Fill Color select element
selectInput(inputId = "color",
label = h5("Fill Color"),
choices = c("brown", "yellow", "green", "blue", "red"),
selected = "brown"),
## Add log-scale check box
checkboxInput(inputId = "log",
label = "log-sclae for X-variable in Scatterplot?",
value = FALSE),
## Add Y-Variable select element
selectInput(inputId = "var_y",
label = h5("Y-Variable"),
choices = c("Structure.Cost", "Land.Value", "Home.Value", "Home.Price.index"),
selected = "Structure.Cost"),
## Add Circle-Size side bar
sliderInput(inputId = "size",
label = h5("Circle-Size"),
min = 1,
max = 10,
value = 3),
## Add Outlier color select element
selectInput(inputId = "color_out",
label = h5("Outlier Color"),
choices = c("white", "yellow", "green", "blue", "red"),
selected = "white")
),
mainPanel(
tabsetPanel( # Establish tabset panel
tabPanel(
# Tab1
title = "Histogram",
value = plotOutput(outputId = "hist") # Add an figure in tab1
),
tabPanel(
# Tab2
title = "Scatterplot",
value = plotOutput(outputId = "scatter") # Add an figure in tab2
)
)
)
)
))
My code in server.R:
library(shiny)
library(ggplot2)
library(sp)
library(dplyr)
# setwd()
landdata = read.csv("landdata.csv")
options(scipen = 999)
shinyServer(function(input, output) {
## Plotting Histogram
output$hist = renderPlot({
# Plotting
if (input$log == FALSE){
ggplot(landdata, aes_string(x = input$var_x)) +
geom_histogram(color = input$color)
}else{
ggplot(landdata, aes_string(x = input$var_x)) +
geom_histogram(color = input$color) +
scale_x_log10(input$var_x)
}
})
## Plotting Scatter plot
output$scatter = renderPlot({
# Data pre-processing
p = ggplot(data = landdata, aes_string(x = input$var_x, y = input$var_y)) +
geom_point() +
stat_ellipse(type = "norm", level = 0.95, color = "black")
build = ggplot_build(p)$data
pts = build[[1]]
elli = build[[2]]
Outlier = point.in.polygon(pts$x, pts$y, elli$x, elli$y)
landdata = cbind(landdata, Outlier)
landdata$Outlier = ifelse(landdata$Outlier == 0, yes = "Y", no = "N") %>% factor(level = c("Y", "N"))
# Plotting
if (input$log == FALSE){
ggplot(landdata, aes_string(x = input$var_x, y = input$var_y)) +
geom_point(aes(color = Outlier), size = input$size) +
scale_color_manual(values = c(input$color, input$color_out))
}else{
ggplot(landdata, aes_string(x = input$var_x, y = input$var_y)) +
geom_point(aes(color = Outlier), size = input$size) +
scale_color_manual(values = c(input$color, input$color_out)) +
scale_x_log10(input$var_x)
}
})
})
The mistake lies in the tabPanel setup. value is not the correct argument for the plot. value is "the value that should be sent when tabsetPanel reports that this tab is selected" (taken from the manual). That means, value has the role of an id (like id argument of tabsetPanel or outputId of plotOutput).
Remove value = to make it work (the code snippet below gave me an output on my system).
tabsetPanel( # Establish tabset panel
tabPanel(
# Tab1
title = "Histogram",
plotOutput(outputId = "hist") # Add an figure in tab1
),
tabPanel(
# Tab2
title = "Scatterplot",
plotOutput(outputId = "scatter") # Add an figure in tab2
)
)

Update radio button after action button input shiny

I'm creating a shiny app, and I want one of my tabs to be a 13 question quiz/game. However, I don't want all 13 questions displayed at once. I want to include an action button that when the user presses, the next question is displayed. Currently, both questions are displayed. Also, will I need to create separate action buttons for each question?
Problem 2: Questions 1-5 use the same plot. Questions 6-13 will use a different plot, and I will want both the question and the plot to be changed after question 5. I've provided 2 questions as an example.
In my UI script I have:
navbarPage(
"NEO Guess Who", position = "fixed-top",
tabPanel("Quiz",
fluidPage(
titlePanel(h1("Do you even know us?")),
sidebarLayout(
sidebarPanel(
radioButtons("q1", "Whose personality is plotted as the purple line?",
choices = list("Amy" = "Amy",
"Claire" = "Claire",
"Olivia" = "Olivia",
"Shae" = "Shae",
"Sharon" = "Sharon"),
selected = character(0)),
textOutput("q1text"),
actionButton("q1action", "Next", class = "btn-success"),
radioButtons("q2", "Whose personality is plotted as the blue line?",
choices = list("Amy" = "Amy",
"Claire" = "Claire",
"Olivia" = "Olivia",
"Shae" = "Shae",
"Sharon" = "Sharon"),
selected = character(0))),
mainPanel(
plotOutput("plot7"))
)))
)
within the server script, I have:
output$q1text <- renderText({
q1 <- switch (input$q1,
Amy = paste("Oops, the correct answer is Sharon"),
Claire = paste("Oops, the correct answer is Sharon"),
Olivia = paste("Oops, the correct answer is Sharon"),
Shae = paste("Oops, the correct answer is Sharon"),
Sharon = paste("Correct!"),
)
})
observeEvent(input$q1action, {
updateRadioButtons(session, "q1", choices = c("Amy", "Claire", "Olivia", "Shae", "Sharon"), selected = 0)
updateRadioButtons(session, "q2", choices = c("Amy", "Claire", "Olivia", "Shae", "Sharon"), selected = 0)
})
# both questions are still displayed
# no legend
output$plot7 <- renderPlot({
{neo_simple <- read.csv("neo_simple.csv", header = T, sep = ",")}
{neo_simple$domain <- factor(neo_simple$domain, levels = c("neuroticism", "extraversion", "openness", "agree", "conscient"))}
{neoColors <-
setNames( c('#a6cee3', '#b2df8a', '#fb9a99', '#fdbf6f', '#cab2d6'),
levels(neo_simple$id) )}
neo_simple %>%
ggplot(aes(x = domain, y=tscore, group = id, color = id)) +
geom_point(size = 1.75) +
scale_color_manual(values = neoColors) +
geom_line(size = 1.25) +
theme_bw() +
ggtitle("NEO Domain Scores") +
theme(plot.title = element_text(hjust = 0.5, size = 15)) +
theme(text = element_text(size=rel(4.5))) +
theme(legend.position = "none") +
theme(plot.caption = element_text(hjust = 0, size = 14))
})
Perhaps the 'slickR' package is a possible way:
library(shiny)
library(slickR)
ui <- fluidPage(
slickROutput("questions", width = "50%")
)
server <- function(input, output, session){
output[["questions"]] <- renderSlickR({
slickR(
slick_list(
radioButtons(
"q1",
"First question",
choices = c("Yes", "No")
),
radioButtons(
"q2",
"Second question",
choices = c("True", "False")
)
)
)
})
}
shinyApp(ui, server)

Shiny app does not load properly

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.

Passing Functions to Reactives in R-Shiny

Issue:
I'm interested in displaying three graphs in a shiny web app. I have written three functions to graph each type of plot for a specified range. The function's parameter takes a input parameter, region, and subsets the larger data.frame for that specified region and subsequently graphs it.
I'm having difficulty passing this function into an r-shiny reactive element.
Here is my function:
plot_30cumulative <- function(enter_region) {
subset <<- HPF[HPF$region == enter_region, ]
thirty_year_cumulative <<- ggplot(subset, aes(x=subset$date)) +
geom_line(aes(y = subset$BaseCumulative, color = "Base"), color = "green") +
geom_line(aes(y = subset$StressCumulative, color = "Adjusted"), color = "red", linetype = "dashed") +
theme_bw() +
scale_x_date(name = "",
date_labels = "%Y-%m-%d",
limits = as.Date(c("2014-02-15", "2044-02-15")),
breaks = seq(as.Date("2014-02-15"), as.Date("2044-02-15"), by = "1 year")) +
scale_y_continuous(name = "Cumulative Growth Rates",
breaks = seq(min(subset$StressCumulative),max(subset$BaseCumulative), .25),
limits = c(NA, 4), # Temporarily hard-coded for better visability.
labels = percent) +
theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
ggtitle("Cumulative 30-Year Growth Rates")
What I Want in Shiny:
library(shiny)
#Define UI for dataset
ui <- fluidPage(
#App title ----
titlePanel("Home Price Forecasting under Stress Scenarios"),
sidebarLayout(
sidebarPanel(
#Input: Stress Path Function Parameters ----
#Input: Numeric entry for region to plot ----
numericInput(inputId = "region",
label = "Enter Region Number:",
value = "1",
min = 1,
max = 110)
),
# Main panel for displaying outputs ----
mainPanel(plotOutput(outputId = "ThYrC"),
plotOutput(outputId = "FiYrC"),
plotOutput(outputId = "FoYrQtr")
)
)
)
#Define server logic to summarize and view selected dataset ----
server <- function(input, output){
output$ThYrC <- renderPlot({reactive(plot_30cumulative(enter_region == input$region)}))
}
# Run the application ----
shinyApp(ui = ui, server = server)
Problem:
I can't seem to pass the function parameter, enter_region, to the reactive element by input$region == enter_region.
Any insight into this issue would be much appreciated!

Basic shiny not rendering plot

I have this shiny code and the plot is not showing for some reason. Can you please extend me a hand?
Is a basic shiny plot to render in the Main Panel. Checked loads of times and still not plotting.
library(shiny)
library(plotly)
library(ggplot2)
ui <- fluidPage(
(titlePanel("APP & MEP | Size (m2) ~ Hours", windowTitle = "app")),
sidebarLayout(
sidebarPanel(
checkboxGroupInput(inputId = "checkgroup",
label = "Select Deparments",
choices = c("All", "ELE", "HVAC", "MAN", "PH", "LV"),
selected = "All", inline = F),
radioButtons(inputId = "radio",
label = "ADD Stat_Smooth?",
choices = c("YES","NO"),
inline = T),
sliderInput(inputId = "slider",
label = "SPAN Setting",
min = 0.2, max = 2, value = 1,
ticks = T)
),
mainPanel(plotOutput(outputId = "plot33"))
)
)
server <- function(input, output){
output$plot33 <- renderPlotly({
gg <- ggplot(sizedf, aes(SIZE, Hours)) + geom_point(aes(color = Department)) + ggtitle("Size(m2) vs Hours per department")
p <- ggplotly(gg)
p
})
}
shinyApp(ui = ui, server = server)
I have seen this same mistake a few time already.
plotlyOutput() should be used, not plotOutput()

Resources