FiofanS
FiofanS

Reputation: 309

Count the number of occurances of values in ggplot

I have the following data:

df = data.frame(c("2012","2012","2012","2013"),
                c("tuesday","tuesday","friday","thursday"),
                c("AAA","BBB","AAA","AAA"))
colnames(df) = c("year","day","type")

I want to show the number of occurances (absolute frequency) of type values (AAA, BBB) per year and day. Currently I wrote the following code, but it requires that I add one more dimension to aes, e.g. aes(type, some_dimension, fill = as.factor(year)). So, how can I add something like count(type)?

ggplot(dat) +
  geom_bar(aes(type, fill = as.factor(year)), 
           position = "dodge", stat = "identity") + 
  facet_wrap(~day)

Upvotes: 3

Views: 14230

Answers (1)

Marta
Marta

Reputation: 3152

In geom_bar change stat from "identity" to "count", like here:

library("ggplot2")

ggplot(df) +
    geom_bar(aes(x = type, fill = as.factor(year)), 
             position = "dodge", stat = "count") + 
    facet_wrap(~day)

Upvotes: 5

Related Questions