mmyoung77
mmyoung77

Reputation: 1417

R ggplot: stat = "identity" is not working for some reason

I have a datafile which looks something like this...

Rate <- runif(14, 0, 20)
Day <- c("Sunday", "Monday", "Tuesday", 
         "Wednesday", "Thursday", "Friday", "Saturday", 
         "Sunday", "Monday", "Tuesday", 
         "Wednesday", "Thursday", "Friday", "Saturday")
Grouper <- c(rep(1, 7), rep(2, 7))
df <- data.frame(Rate, Day, Grouper)

...and I want to make a bar chart with two bars for each day: one bar for Grouper = 1 and one bar for Grouper = 2. The y-value is not a count, it's the Rate variable, so I need to use stat = "identity" to make it work...

# Set max chart height
maxlimit = max(df$Rate) * 1.1
# Actual plot code 
ggplot(df, aes(Day, Rate)) +
  geom_bar(stat = "identity") +
  geom_bar(aes(fill = Grouper), position = "dodge") + 
  scale_y_continuous(limits = c(0, maxlimit)) + 
  theme_classic()

...but I am still getting the error stat_count() must not be used with a y aesthetic. Can someone explain to me why I am getting this error and what I can do to fix it?

Upvotes: 0

Views: 1856

Answers (1)

mmyoung77
mmyoung77

Reputation: 1417

My mistake was calling geom_bar twice. I thought I was supposed to do this, but I was wrong; the second call just re-sets the geom_bar settings, thus erasing the call to stat=identity. This code works:

ggplot(TSdata, aes(Day, Rate, group = Grouper, col = Grouper)) +
  geom_bar(stat = "identity", aes(fill = Grouper), position = "dodge") + 
  scale_y_continuous(limits = c(0, maxlimit)) + 
  theme_classic()

Upvotes: 1

Related Questions