FiofanS FiofanS - 1 month ago 9
R Question

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)

Answer

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