rggplot2reorderlist

How can I reorder the graph using cord polar with 'y' as a simple count ggplot2?


I am trying to sort the graph by count, but I am not clearly getting how I can. Important thing is that 'topic' is a discrete variable and I'm just showing the count of each topic through the whole data set. This is the code I am using:

ggplot(data = dtd, aes(x = topic)) + geom_bar(fill = "lightblue", colour = "black") + coord_polar()

And this is the error when I try to reorder:

 ggplot(data = dtd, aes(x = reorder(topic))) + geom_bar(fill = "lightblue", colour = "black") + coord_polar()
Error in tapply(X = X, INDEX = x, FUN = FUN, ...) : 
  argument "X" is missing, with no default

It'd be a plus if someone might say how I could fill those sections with a gradient blue shade or something pretty.


Solution

  • The error is coming from reorder not having a second vector of values to reorder by. You could supply one by counting up your data ahead of passing to ggplot, then reordering it by the new variable:

    library(dplyr)
    library(ggplot2)
    
    df <- tibble(Topic = c(rep("A", 55), rep("B", 22), rep("C", 40), rep("D", 100)))
    
    df %>%
      group_by(Topic) %>% 
      summarise(freq = n()) %>% 
      ggplot(aes(x = reorder(Topic, freq), y = freq)) + 
      geom_bar(fill = "lightblue", colour = "black", stat = "identity") +
      coord_polar()
    

    There may be smoother ways of doing it, but this keeps the reorder function you were using before.