Changing y-Axis Range for ggplot boxplot in Shiny using coord_cartesian()

Hello everbody,

I am trying to create a dynamic Shiny Boxplot where the user can also changing the y-axis range value as they want. Here is just an example using the mtcars data:


library(shiny)
library(ggplot2)

ui <- fluidPage(
    titlePanel("Boxplot"),
    sidebarLayout(
        sidebarPanel(
            textInput("yAxisRange","Y-axis range (eg., '0,10'):")
        ),

        mainPanel(
           plotOutput("distPlot")
        )
    )
)

# Define server logic required to draw a histogram
server <- function(input, output) {

    output$distPlot <- renderPlot({
        ggplot(mtcars, aes_string(x=as.factor(mtcars$vs),y=mtcars$mpg)) +
            stat_boxplot(geom ='errorbar', width = 0.5) + #add end of the whisker line
            geom_boxplot(outlier.shape = NA)+
            coord_cartesian(ylim = c(input$yAxisRange)) #change the y-axis range
    })
}

# Run the application 
shinyApp(ui = ui, server = server)

and it gives an error "missing value where TRUE/FALSE needed". Can someone help me with this one? thank you!

I would avoid using a textInput here, as this might be a source for errors, when the user types in something wrong.
Also this makes it difficult to handle as you actually input a string as "0,10", that you need to split into 2 entries and convert it to a vector to further handle this in the plot...
You could use 2 numeric inputs for the min and the max or a sliderinput with 2 sliders:


sliderInput("yAxisRange","Y-axis range:",  min = 0, max = 100, value = c(0,50))
1 Like

PS: Here a possible strategy to separate the string and combine it back, please see the "plotrange"-insert.

server <- function(input, output) {
  
  plotrange = reactive({
    Num1 = as.numeric(str_split(input$yAxisRange, 
                     ",", simplify = TRUE)[[1]])
    Num2 = as.numeric(str_split(input$yAxisRange, 
                                ",", simplify = TRUE)[[2]])
    range = c(Num1, Num2)
    return(range)
  })
  
  output$distPlot <- renderPlot({
    ggplot(mtcars, aes_string(x=as.factor(mtcars$vs),y=mtcars$mpg)) +
      stat_boxplot(geom ='errorbar', width = 0.5) + #add end of the whisker line
      geom_boxplot(outlier.shape = NA)+
      coord_cartesian(ylim = plotrange() ) #change the y-axis range
  })
}
2 Likes

Thank you so much! but is that should be strsplit or str_split? str_split does not work for me.

Ah okay, old habit. str_split() is part of the stringr package, I usually use the tidyverse library and it's included there.
You could also use strsplit or can even think of using grep().
For strsplit() it could be realised with:
Num1 = as.numeric(strsplit(input$yAxisRange, ",")[[1]][1])
Num2 = as.numeric(strsplit(input$yAxisRange ",")[[1]][2])

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

If you have a query related to it or one of the replies, start a new topic and refer back with a link.