Washington Muniz
Washington Muniz

Reputation: 100

r - Sorting of Barts-ggplot2 in shiny using reactive

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.

Upvotes: 0

Views: 221

Answers (1)

Duck
Duck

Reputation: 39595

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")
  
  })
  }

Upvotes: 1

Related Questions