Created
December 13, 2012 18:30
-
-
Save mattbaggott/4278520 to your computer and use it in GitHub Desktop.
demonstration of plotting distributions overlapping lineplots in R
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## | |
## demonstration of distributions overlapping on lineplots | |
## [email protected] | |
## Dec 11, 2012 | |
## | |
## in response to: http://stats.stackexchange.com/questions/45591/r-plot-time-indexed-densities/45614#45614 | |
library(ggplot2) # for plotting | |
library(lubridate) # for getting year from dates in dataset | |
library(plyr) # for getting annual mean easily | |
data(economics) # sample dataset | |
# calculate year to group by using lubridate's year function | |
economics$year <- year(economics$date) | |
# get a subset | |
subgrp <- economics[economics$year>2001&economics$year<2007,] | |
# get the mean of each year | |
subgrp <- ddply(subgrp, .(year), mutate, mean=mean(unemploy)) | |
# plot | |
ggplot(subgrp, aes(x=date, y=unemploy))+ | |
geom_violin(aes(group=year, colour=year, fill=year), alpha=0.5, | |
kernel="rectangular")+ # passes to stat_density, makes violin rectangular | |
xlab("Year")+ # label one axis | |
ylab("Unemployment")+ # label the other | |
coord_flip()+ # flip the axes so violin plots are sideways | |
theme_bw()+ # make background white | |
theme(legend.position="none")+ # suppress legend for year colors | |
geom_line(aes(x=date, y=mean, # add a line for the mean | |
group=year),colour="purple")+ | |
geom_line(size=1.5) # make line for monthly data |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment