drtamakloe
drtamakloe

Reputation: 127

Creating a grouped bar plot in R with bars unarranged

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.

Upvotes: 0

Views: 98

Answers (1)

ktiu
ktiu

Reputation: 2626

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

Upvotes: 1

Related Questions