0

I am using Shiny code in R to produce multiple(30) Boxplots. I have about 30 categories (x-axis) that I am trying to display side by side and want to adjust the x-axis on the bottom so that I can see each of the names at a 90 degree angle. I tried putting conditions in the 'ggplot' & the 'plotly' line to adjust the x-axis / y-axis but it does nothing on the Shiny app. I also want to adjust the y-axis tick marks so that they tick at every $1000 value. I can reproduce the graph using ggplot2 and adjust the x/y-axis, but want to make my graph dynamic with Shiny so I can apply different filters. I am trying to plot 'Name' (X-axis, categorical) vs 'Dollar' (Y-axis, numerical) and have about 30 different 'Names' I would like to view. My data has 10K+ rows.

Sample Data:
ID      Tradelane     Name     Dollar
10R46   Ocean         Ray      2000
10R41   Air           Jay      1000
10R45   Truck         Alfred   500
10R49   Ocean         Mark     5

Would appreciate any help, below is my code:

library(shiny)
library(plotly)

data(supply)
nms <- names(supply)

ui <- fluidPage(

  headerPanel("Supply Metrics"),
  sidebarPanel(
    sliderInput('sampleSize', 'Sample Size', min = 1, max = nrow(supply),
                value = 1000, step = 500, round = 0),
    selectInput('x', 'X', choices = nms, selected = "name"),
    selectInput('y', 'Y', choices = nms, selected = "dollar"),
    selectInput('color', 'Color', choices = nms, selected = "tradelane"),

    selectInput('facet_row', 'Facet Row', c(None = '.', nms), selected = "tradelane"),
    selectInput('facet_col', 'Facet Column', c(None = '.', nms)),
    sliderInput('plotHeight', 'Height of plot (in pixels)', 
                min = 100, max = 2000, value = 1000)
  ),
  mainPanel(
    plotlyOutput('trendPlot', height = "900px")
  )
)

server <- function(input, output) {

  #add reactive data information. Dataset = built in diamonds data
  dataset <- reactive({
    supply[sample(nrow(supply), input$sampleSize),]
  })

  output$trendPlot <- renderPlotly({

    # build graph with ggplot syntax
    p <- ggplot(dataset(), aes_string(x = reorder(input$x, input$y, FUN = median) y = input$y, color = input$color)) + 
      geom_boxplot() + theme(axis.text.x=element_text(size=2,angle=90))



    # if at least one facet column/row is specified, add it
    facets <- paste(input$facet_row, '~', input$facet_col)
    if (facets != '. ~ .') p <- p + facet_grid(facets)

a <- list(size=3, color = "black", tickangle = 45)

ggplotly(p) %>% 
  layout(height = input$plotHeight, xaxis = a, yaxis = a))

  })

}

shinyApp(ui, server)
  • 1
    Can you get the desired results *outside* of `shiny`? If not, then I suggest you reduce this question significantly to be just `ggplot2`, no `shiny`. Perhaps you can also fix that *we have no idea what your data looks like*. (By this I do not mean "describe the data" ... I mean read one or more of (https://stackoverflow.com/questions/5963269, https://stackoverflow.com/help/mcve, and https://stackoverflow.com/tags/r/info) and then provide a sufficient sample of your data to get the point across. – r2evans Nov 07 '18 at 22:27
  • 1
    Thanks @r2evans (apologies first time posting on Stackoverflow). Yes I can reproduce the results using ggplot2, only reason I want to use Shiny is so I can apply and view different fitlers, have added my data sample into the question – user1457741 Nov 07 '18 at 23:46

1 Answers1

0

There are a few things I've noticed:

  1. You've got some errors in your code. Missing commas in ggplot calls, extraneous closing brackets.
  2. Names have to match. Your data has capitalized column names, your input selectors do not. That will cause some errors.
  3. Set your theme aspects either in the ggplot call using theme or using plotly::layout().
  4. If you want 1000 dollar breaks in the y, you'll have to build the logic in to do it when Dollars is selected for that axis, else it'll throw errors. To do so, I would use scale_y_continuous and set the breaks argument accordingly. If you want dollar labels you can use the scales packages and the dollar() function in labels. e.g. scale_y_continuous(breaks = seq(0,3000,1000), labels = dollar)
  5. Your reorder call isn't working as intended, you're giving the function strings and it doesn't like that.

If you remove the above errors, I can make this work. However, I haven't built in the dollars request on the axis labels.

library(shiny)
library(plotly)
library(ggplot2)

supply <- tibble::tribble(
  ~ID,      ~Tradelane,     ~Name,     ~Dollar,
"10R46",   "Ocean",         "Ray", 2000,
"10R41",   "Air",           "Jay", 1000,
"10R45",   "Truck",         "Alfred",   500,
"10R49",   "Ocean",         "Mark", 5)

# data(supply)
nms <- names(supply)

ui <- fluidPage(

  headerPanel("Supply Metrics"),
  sidebarPanel(
    sliderInput('sampleSize', 'Sample Size', min = 1, max = nrow(supply),
                value = 1000, step = 500, round = 0),
    selectInput('x', 'X', choices = nms, selected = "Dame"),
    selectInput('y', 'Y', choices = nms, selected = "Dollar"),
    selectInput('color', 'Color', choices = nms, selected = "Tradelane"),

    selectInput('facet_row', 'Facet Row', c(None = '.', nms), selected = "Tradelane"),
    selectInput('facet_col', 'Facet Column', c(None = '.', nms)),
    sliderInput('plotHeight', 'Height of plot (in pixels)', 
                min = 100, max = 2000, value = 1000)
  ),
  mainPanel(
    plotlyOutput('trendPlot', height = "900px")
  )
)

server <- function(input, output) {

  #add reactive data information. Dataset = built in diamonds data
  dataset <- reactive({
    supply[sample(nrow(supply), input$sampleSize),]
  })

  output$trendPlot <- renderPlotly({

    # build graph with ggplot syntax
    p <- ggplot(dataset(), aes_string(x = input$x, y = input$y, color = input$color)) + 
      geom_boxplot() 


    # if at least one facet column/row is specified, add it
    facets <- paste(input$facet_row, '~', input$facet_col)
    if (facets != '. ~ .') p <- p + facet_grid(facets)

    a <- list(tickangle = 45)

    ggplotly(p) %>% 
      layout(height = input$plotHeight, xaxis = a)

  })

}

shinyApp(ui, server)
Jake Kaupp
  • 7,892
  • 2
  • 26
  • 36
  • Thanks to everyone for the help, I made the changes and now the chart is loading properly, appreciate all the support :) ! – user1457741 Nov 08 '18 at 05:50