Supposing your data is in a dataframe called df
, you can do that with the help of the dplyr
and tidyr
packages:
library(dplyr)
library(tidyr)
wide <- df %>% select(date,classes) %>%
group_by(date,classes) %>%
summarise(n=n()) %>% # as @akrun said, you can also use tally()
spread(classes, n, fill=0)
Using the example data you provided, this results in the following dataframe:
date english french spanish
9/1/11 1 2 1
9/2/11 1 1 0
9/3/11 0 0 2
9/5/11 2 1 1
Now you can make a lattice
plot with:
barchart(date ~ english + french + spanish, data=wide, stack = TRUE,
main = list(label="Distribution of language classes",cex=1.6),
xlab = list("Number of classes", cex=1.1),
ylab = list("Date", cex=1.1),
auto.key = list(space='right',cex=1.2,text=c('Enligsh','French','Spanish')))
which gives the following plot:
EDIT: Instead of using lattice-plots, you can also use ggplot2
, which is (at least in my opinion) easier to understand. An example:
# convert the wide dataframe to a long one
long <- wide %>% gather(class, n, -date)
# load ggplot2
library(ggplot2)
# create the plot
ggplot(long, aes(date, n, fill=class)) +
geom_bar(stat="identity", position="stack") +
coord_flip() +
theme_bw() +
theme(axis.title=element_blank(), axis.text=element_text(size=12))
which gives: