How to Check if ggplot input is NULL

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 {}
}

You can figure out what's going wrong by running dplyr::filter(Marriage, FALSE) outside of your shiny app — that will select 0 rows so you can figure out a better condition to use (it's not going to be NULL).

1 Like

Hello, thank you for your reply. I will work on this.

I tried the following. Why do I still get forcats warning?

#1 I execute

plotdata <- dplyr::filter(Marriage, FALSE) %>% count(officialTitle)

  if (nrow(plotdata) > 0){
    str <- paste("nrows > 0. Number of rows is ", nrow(plotdata))
    print(str)
    print(plotdata)

But I get the following:

[1] "nrows > 0. Number of rows is  1"
# A tibble: 1 x 2
  officialTitle     n
  <fct>         <int>
1 NA                0
Warning message:
Factor `officialTitle` contains implicit NA, consider using `forcats::fct_explicit_na`

#2 I heed the warning and execute the following

plotdata <- dplyr::filter(Marriage, FALSE) %>% count(officialTitle)
plotdata$officialTitle <- fct_explicit_na(plotdata$officialTitle)

  if (nrow(plotdata) > 0){
    str <- paste("nrows > 0. Number of rows is ", nrow(plotdata))
    print(str)
    print(plotdata)

This is the result:

[1] "nrows > 0. Number of rows is  1"
# A tibble: 1 x 2
  officialTitle     n
  <fct>         <int>
1 (Missing)         0
Warning message:
Factor `officialTitle` contains implicit NA, consider using `forcats::fct_explicit_na` 

#3 Then I think maybe this has nothing to do with forcats. I delete the forcats statement and remove na from plotdata, ie

plotdata <- dplyr::filter(Marriage, FALSE) %>% count(officialTitle)
plotdata <- na.omit(plotdata)

  if (nrow(plotdata) > 0){
    str <- paste("nrows > 0. Number of rows is ", nrow(plotdata))
    print(str)
    print(plotdata)

Output is following:

[1] "nrows < 0. Number of rows is  0"
# A tibble: 0 x 2
# ... with 2 variables: officialTitle <fct>, n <int>
Warning message:
Factor `officialTitle` contains implicit NA, consider using `forcats::fct_explicit_na`

Complete Code:

# Load packages ----
library(shiny)
library(ggplot2)
library(dplyr)
library(scales)
library(treemapify)
library(forcats)

# Load data ----
data(Marriage, package="mosaicData")

plotdata <- dplyr::filter(Marriage, FALSE) %>% count(officialTitle)
#plotdata$officialTitle <- fct_explicit_na(plotdata$officialTitle)
plotdata <- na.omit(plotdata)

  if (nrow(plotdata) > 0){
    str <- paste("nrows > 0. Number of rows is ", nrow(plotdata))
    print(str)
    print(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 {
    str <- paste("nrows < 0. Number of rows is ", nrow(plotdata))
    print(str)
    print(plotdata)
  }

Right, you should be checking the number of rows with nrow() not if the object is NULL with is.null().

1 Like

Then how to resolve the forcats warning? What else can I try?

I doubt it's important; I wouldn't worry about it.

1 Like

OK, thank you --- you're the best!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.