I have been unable to find a simple analog for plotting a line graph from a table object in ggplot2. Given the elegance and utility of the package, I feel I must be missing something quite obvious. As an illustration consider a data frame with yearly observations:
dat<-data.frame(year=sample(c("2001":"2010"),1000, replace=T))
And a quick time series plot in base R:
plot(table(dat$year), type="l")
Switching to qplot, returns the error “attempt to apply a non-function”:
qplot(table(dat$year), geom="line")
ggplot2 requires a data frame. Fair enough. But this returns the same error.
qplot(year, data=dat, geom="line")
After some searching and fiddling, I abandoned qplot, and came up with the following approach which involves specifying a line geometry, binning the counts, and dropping final values to avoid plotting zeros.
ggplot(dat, aes(year) ) + geom_line(stat = "bin", binwidth=1, drop=TRUE)
It seems like rather a long walk around the block. And it is still not entirely satisfactory, since the bins don’t align precisely with the mid-year values on the x-axis. Where have I gone wrong?
Maybe still more complicated than you want, but:
(the
group=1is necessary because the Year variable (Var1) is returned as a factor …)If you didn’t need it as a one-liner you could use
ytab <- as.data.frame(table(dat$year))first to extract the table and convert it to a data frame …Following Brian Diggs’s answer, if you’re willing to construct a bit more
fortifymachinery you can condense this a bit more:A utility function that converts a factor to numeric if possible:
And a
fortifymethod that turns the table into a data frame and then tries to make the columns numeric:Now this works almost as you would like it to:
(It would be nice/easier if there were a
tableoption to preserve the numeric nature of cross-classifying factors …)