Tanga94
Tanga94

Reputation: 837

Maintain the same order for variables in geom_bar with fill argument

I have the following dataframe:

data <- structure(list(Date = structure(c(1L, 2L, 3L, 4L, 1L, 2L, 3L, 
4L), .Label = c("Mar-2021", "Jun-2021", "Sep-2021", "Dec-2021"
), class = "factor"), Key = c("Previous Forecast", "Previous Forecast", 
"Previous Forecast", "Previous Forecast", "Current Forecast", 
"Current Forecast", "Current Forecast", "Current Forecast"), 
    Value = c("3.1", "3.4", "3.3", "3.0", "2.8", "4.1", "3.8", 
    "3.7")), row.names = c(NA, -8L), class = c("tbl_df", "tbl", 
"data.frame"))

When I create a simple barplot, for some reason the fill argument changes the order of the bars from the second month. Is there a way to maintain the same order (red bar before blue bar) for each month?

library(ggplot2)

ggplot(data, aes(fill=Key, y=Value, x=Date)) + 
  geom_bar(position=position_dodge(), stat="identity") 

enter image description here

Upvotes: 2

Views: 139

Answers (1)

zx8754
zx8754

Reputation: 56004

Keep numbers as numeric class:

data$Value <- as.numeric(data$Value)

ggplot(data, aes(fill = Key, y = Value, x = Date)) + 
  geom_bar(position = position_dodge(), stat = "identity")

enter image description here

Upvotes: 2

Related Questions