How to check if Plotdata is null.
My program takes inputs for race and age range and sends to plot_it
plotdata
will get rows based on user's selection, i.e.
plotdata <- dplyr::filter(Marriage, race %in% what_races, age >= what_ages[1], age <= what_ages[2]) %>% count(officialTitle)
BUT, I don't want anything to output if there are no rows and I tried
if (!is.null(plotdata))
then draw plot, but that still gives error
When I select "Hispanic", "Native American" and age range 20 to 20, I get following errors on console
Warning: Factor `officialTitle` contains implicit NA, consider using `forcats::fct_explicit_na`
Warning: Error in : Must request at least one colour from a hue palette.
But there are no NAs in officialTitle
. Try the following you will see this:
> library(shiny)
> data(Marriage, package="mosaicData")
> write.csv(Marriage,"file.csv")
Please help!
Folder "marriage" has "app.R" and "helpers.R"
app.R
# Load packages ----
library(shiny)
library(ggplot2)
library(dplyr)
library(scales)
library(treemapify)
# Source helpers ----
source("helpers.R")
# Load data ----
data(Marriage, package="mosaicData")
# User interface ----
ui <- fluidPage(
titlePanel(h4("Marriage Records")),
sidebarLayout(
sidebarPanel(helpText("Marriage records from the Mobile County, Alabama, probate court."),
checkboxGroupInput("race","Races to show",
c("White", "Black","American Indian", "Hispanic")),
sliderInput("age", "Age Range:",min = as.integer(min(Marriage$age)), max = as.integer(max(Marriage$age)),value = c(min,max))),
mainPanel(plotOutput("chart"))
)
)
server <- function(input, output) {
output$chart <- renderPlot({
what_races <- input$race
what_ages<- c(input$age[1],input$age[2])
if ((length(what_races) > 0 ) & !is.null(what_ages)) {
plot_it(what_races,what_ages)
}
})
}
# Run the app
shinyApp(ui, server)
helpers.R
plot_it <- function(what_races,what_ages) {
plotdata <- dplyr::filter(Marriage, race %in% what_races, age >= what_ages[1], age <= what_ages[2]) %>%
count(officialTitle)
if (!is.null(plotdata)){
ggplot(plotdata,
aes(fill = officialTitle,
area = n,
label = officialTitle)) +
geom_treemap() +
geom_treemap_text(colour = "white",
place = "centre") +
labs(title = "Marriages by officiate") +
theme(legend.position = "none")
}
else {}
}