Cannot add ggproto objects together

Viewed 1399

I'm currently working on an Rshiny app. I had to make multiple boxplots with several select inputs and a checkbox input. I've almost finished my task and now I just need to make it so that every time I change the Species selected, the scale stays the same (unless other variables have been input of course).

My code looks like this:

library(shiny)
library(palmerpenguins)
library(dplyr)
library(ggplot2)

data <- na.omit(penguins)

colnames(data) <- c("Species",
                    "Island",
                    "Bill Length (mm)",
                    "Bill Depth (mm)", 
                    "Flipper Length (mm)",
                    "Body Mass (g)",
                    "Sex",
                    "Year")

data.numeric <- data[, c(3:6, 8)]

data.categorical <- data[, c(1,7)]


ui <- fluidPage(
  headerPanel("Penguin boxplots"),
  selectInput("ycol", 
              "Numeric Variable", 
              names(data.numeric),
              selected = names(data.numeric)[3]),
  selectInput("xcol",
              "Categorical Variable",
              names(data.categorical),
              selected = names(data.categorical)[2]),
  checkboxInput("split",
                "Split levels by Island",
                value = FALSE),
  selectInput("species",
              "Species Type",
              c("Unspecified", levels(data$Species))),
  mainPanel(
    plotOutput("plot1")
  ))






# 4. Use a select input to allow the user to view separate plotting 
# panels for each species, with each plot panel on the same scale.


server <- function(input, output){
  output$plot1 <- renderPlot({
    par(mar = c(5, 4.1, 0, 1))
    
    if (input$species == "Unspecified"){
      
      
      
      
      if (input$split) {
        ggplot(data, aes(x = data[[input$xcol]], y = data[[input$ycol]], fill = Island)) +
          geom_boxplot(na.rm = TRUE) +
          
          if (input$ycol == "Bill Length (mm)"){
              coord_cartesian(ylim = c(30, 60)) 
          } else if (input$ycol == "Bill Depth (mm)"){
            coord_cartesian(ylim = c(12.5, 21.5)) 
          } else if (input$ycol == "Flipper Length(mm)"){
            coord_cartesian(ylim = c(170, 232)) 
          } else if (input$ycol == "Body Mass (g)"){
            coord_cartesian(ylim = c(2500, 6500))
          } else if (input$ycol == "Year"){
            coord_cartesian(ylim = c(2006, 2009))
          } +
          xlab(input$xcol) +
          ylab(input$ycol) + 
          scale_x_discrete(labels = c("Female", "Male")) +
          theme(text = element_text(size = 15))
        
      } else {
        ggplot(data, aes(x = data[[input$xcol]], y = data[[input$ycol]])) +
          geom_boxplot(na.rm = TRUE) +
          if (input$ycol == "Bill Length (mm)"){
            coord_cartesian(ylim = c(30, 60)) 
          } else if (input$ycol == "Bill Depth (mm)"){
            coord_cartesian(ylim = c(12.5, 21.5)) 
          } else if (input$ycol == "Flipper Length(mm)"){
            coord_cartesian(ylim = c(170, 232)) 
          } else if (input$ycol == "Body Mass (g)"){
            coord_cartesian(ylim = c(2500, 6500))
          } else if (input$ycol == "Year"){
            coord_cartesian(ylim = c(2006, 2009))
          } +
          xlab(input$xcol) +
          ylab(input$ycol) +
          theme(text = element_text(size = 15))
      }
      
      
      
      
      
      
      
    } else {
      
      
      
      
      
      data <- data %>%
        filter(data$Species == input$species)
      if (input$split) {
        ggplot(data, aes(x = data[[input$xcol]], y = data[[input$ycol]], fill = Island)) +
          geom_boxplot(na.rm = TRUE) +
          xlab(input$xcol) +
          ylab(input$ycol) + 
          scale_x_discrete(labels = c("Female", "Male")) +
          theme(text = element_text(size = 15))
        
      } else {
        ggplot(data, aes(x = data[[input$xcol]], y = data[[input$ycol]])) +
          geom_boxplot(na.rm = TRUE) +
          xlab(input$xcol) +
          ylab(input$ycol) +
          theme(text = element_text(size = 15))
      }
    }
    
    
  })
}

















shinyApp(ui = ui, server = server)

The issue arises when I run the lines containing else if (input$ycol == "Year"){ coord_cartesian(ylim = c(2006, 2009))} as I get the following error: Cannot add ggproto objects together. Did you forget to add this object to a ggplot object?

I'm not sure where I'm going wrong here or if I'm just overlooking some sort of syntax error.

p.s. The code isn't finished - I still need to add more code to control the scales for when the Species is not 'Unspecified', but I'm not doing that until this is figured out.

1 Answers

You can simplify things by creating a function that returns the desired coord_cartesian statement. The function can then be added to a ggplot chain with + as in the usual ggplot workflow.

The example below uses the hard-coded choices in your example. However, if you can provide more information on how these ranges are selected, it may be possible to get the y-range in a more automated way, rather than having to explicitly hard-code each possible case.

In the example below, the case_when statement returns the appropriate ylim values to feed to coord_cartesian. If input$ycol does not match any of the options, case_when will return ylim=c(NA,NA), which will result in ggplot keeping the default axis range.

# I've included only 3 choices. Add in as many additional choices as needed.
coord_fnc = function(x=input$ycol) {
  ylim = dplyr::case_when(
      x=="Bill Length (mm)" ~ c(30,60),
      x=="Flipper Length(mm)" ~ c(170, 232),
      x=="Bill Depth (mm)" ~ c(12.5,21.5)
  )
  coord_cartesian(ylim=ylim)
}


ggplot(data, aes(x = data[[input$xcol]], y = data[[input$ycol]], fill = Island)) +
  geom_boxplot(na.rm = TRUE) +
  coord_fnc() +
  xlab(input$xcol) +
  ylab(input$ycol) +
  theme(text = element_text(size = 15))

Try it with the built-in mtcars data frame:

ggplot(mtcars, aes(hp, mpg)) + 
  geom_point() + 
  coord_fnc("Bill Length (mm)")

enter image description here

Although the string of if else statements takes a lot of code, that approach can work and I'm not sure why you're getting an error (it might be some other part of the code). For example, this works:

input = list(ycol = "Year")

ggplot(mtcars, aes(hp, mpg)) + 
  geom_point() + 
  if (input$ycol == "Bill Length (mm)"){
    coord_cartesian(ylim = c(30, 60)) 
  } else if (input$ycol == "Bill Depth (mm)"){
    coord_cartesian(ylim = c(12.5, 21.5)) 
  } else if (input$ycol == "Flipper Length(mm)"){
    coord_cartesian(ylim = c(170, 232)) 
  } else if (input$ycol == "Body Mass (g)"){
    coord_cartesian(ylim = c(2500, 6500))
  } else if (input$ycol == "Year"){
    coord_cartesian(ylim = c(2006, 2009))
  }
Related