0

Please find the code below for a shiny App using ggplot2, I do not know how to sort them inside the server.R code.

WIth the below code I am able to display the bar chart and change it but ordering the data seems to be an issue.

ui.R

ui <- fluidPage(
  titlePanel("Perdas no Gefin"),
  theme = shinythemes::shinytheme('yeti'),
    sidebarLayout(
    sidebarPanel(selectInput('mes', 'Selecione o mês', unique(month(roi$Data_Contab))),
      mainPanel(
        tabsetPanel(
          tabPanel('Word', plotly::plotlyOutput('contagem'))
                    ))
  )
)

server.R

server <- function(input, output, session){
  rcontagem <- reactive({
    roi %>%
      filter(month(Data_Contab) == input$mes) %>%
      unnest_tokens(word, Parecer) %>%
      anti_join(stop_words2) %>%
      count(word) %>%
      na.omit() %>%
      top_n(30) %>%
      arrange(desc(n))
      })
  
  output$contagem <- plotly::renderPlotly({
    rcontagem()%>%
    ggplot(aes(x = word, y = n)) +
    geom_col()  +
    # Flip the plot coordinates
    coord_flip() +
    ggtitle("Contagem de palavras")
  
  })
  }

shinyApp(ui = ui, server = server)

Plot without order: enter image description here

I already tried this: Sorting of Bars-ggplot2 in shiny, but it didn't work, probably because I'm using reactive.

Washington Muniz
  • 100
  • 1
  • 1
  • 7
  • 1
    Your y axis (the x axis before flipping) is ordered by the values of word, right? (And the values of word appear to have been clipped.) You need to display them sorted in order. So add an index variable in your `rcontagem` reactive. Something like `%>% mutate(Row=as.factor(row_number()))` at the end of the pipe. Then use `Row` as x variable in the `renderPlotly` graph. To restore the axis labels, use a `scale_x_discrete` to supply labels to the factor. I can't do that for you as you haven't given us the raw data. – Limey Jun 21 '20 at 14:39

1 Answers1

1

You could try something like this on your server side:

server <- function(input, output, session){
  rcontagem <- reactive({
    roi %>%
      filter(month(Data_Contab) == input$mes) %>%
      unnest_tokens(word, Parecer) %>%
      anti_join(stop_words2) %>%
      count(word) %>%
      na.omit() %>%
      top_n(30) %>%
      arrange(desc(n))
      })
  
  output$contagem <- plotly::renderPlotly({
    rcontagem()%>%
    ggplot(aes(x = reorder(word,n), y = n)) +
    geom_col()  +
    # Flip the plot coordinates
    coord_flip() +
    ggtitle("Contagem de palavras")
  
  })
  }
Duck
  • 39,058
  • 13
  • 42
  • 84