0

I want to create a grouped bar plot. I realized that the bars are arranged based on the alphabetical order of the items in the legend. How can I make the code generate the graph without rearranging the bars in the alphabetical order?

library(ggplot2)

# creating dataset
Year <- c(rep("2012" , 3) , rep("2013" , 3) , rep("2014" , 3) , rep("2015" , 3) )
Legend <- rep(c("A" , "X" , "E") , 4)
Count <- abs(rnorm(12 , 0 , 15))
data <- data.frame(Year,Legend,Count)

# Grouped barplt
ggplot(data, aes(fill=Legend, y=Count, x=Year)) + 
  geom_bar(position="dodge", stat="identity")

enter image description here

As seen in the image, the bars have been arranged in the order A, E, X - but i want it in the order as it is in the table (A, X, E).

I hope to get some help with this issue. Thank you.

stefan
  • 90,330
  • 6
  • 25
  • 51
drtamakloe
  • 97
  • 1
  • 7
  • 1
    Try with converting to a factor and setting the levels in the desired order: `factor(Legend, levels = c("A", "X", "E"))` – stefan Jun 03 '21 at 11:43
  • See also https://stackoverflow.com/questions/5208679/order-bars-in-ggplot2-bar-graph/9231857#9231857 or – stefan Jun 03 '21 at 11:49
  • Thanks a lot for the suggestions @stefan. I have tried `+ scale_fill_discrete(limits = c("A", "X", "E"))` but only the legends are affected. The bars are still arranged in alphabetical order. – drtamakloe Jun 03 '21 at 11:52
  • Sorry. My bad. Then try the factor approach. – stefan Jun 03 '21 at 11:54

1 Answers1

1

Below is a snippet that should work for your code. It uses dplyr::mutate() to change the Legend columns to factors.

library(ggplot2)
library(dplyr)

data %>%
  mutate(Legend = factor(Legend, levels = c("A", "X", "E"))) %>%
  ggplot(aes(fill = Legend, y = Count, x = Year)) +
    geom_bar(position = "dodge", stat = "identity")
ktiu
  • 2,606
  • 6
  • 20