Environment: Win 7 HP, R v2.15.1
What I wish to get to:
- Plot y (numeric) vs x (date) with
- labels month-year abbrev, sorted mon+year, las2 vertically aligned
- colours filled by year
- facet-grid by year
I have tried different approaches after reading up different threads in this forum, but unable to get what I need. Need help. Attaching sample data and results.
MySample Data
x <- c("04-01-10","05-01-10","06-01-10","07-01-10","08-01-10","09-01-10","10-01-10","11-01-10","12-01-10","01-01-11","02-01-11","03-01-11","04-01-11","05-01-11","06-01-11","07-01-11","08-01-11","09-01-11","10-01-11","11-01-11","12-01-11","01-01-12","02-01-12","03-01-12","04-01-12","05-01-12","06-01-12")
y <- c(120,210,130,160,190,210,80,70,110,120,140,160,130,200,110,180,210,200,90,60,100,100,120,170,100,180,120)
x is date (character) in mm-dd-yy format tz:IST (Calcutta / Asia) data has only single y value per month which is on the start date of the month
Convert to Data Frame
MySample <- data.frame(x) ## convert to dataframe
MySample$y <- y
load required libraries
require(lubridate)
require(ggplot2)
MySample Base Plot
1) Plot x vs y
ggplot(MySample, aes(MySample$x, MySample$y)) +
geom_bar(y=MySample$y,stat="identity")
Gave me base plot results
2) Plot x vs y + fill=year
ggplot(MySample, aes(MySample$x, MySample$y, fill=year(MySample$x))) +
geom_bar(y=MySample$y,stat="identity")
gave me fills but have 5 fill years with 2010,2010.5,2011,2011.5,2012
I have tried different approaches but running into one error or another.
3) Plot x vs y + fill=year + facet_grid(year)
ggplot(MySample, aes(x, y, fill=year(x))) +
geom_bar(y=MySample$y,stat="identity") +
facet_grid(. ~ year(MySample$x))
Get : Error in layout_base(data, cols, drop = drop) : At least one layer must contain all variables used for facetting
4) Plot x vs y + fill=year + facet_grid(year) + labels-month (abbr)
ggplot(MySample, aes(x, y, fill=year(x))) +
geom_bar(y=MySample$y,stat="identity") +
scale_x_date(labels=month(MySample$x,label=TRUE,abbr=TRUE))
Get : Error in scale_labels.continuous(scale, major) : Breaks and labels are different lengths
I'm stuck and need help to move forward. Need solutions to address the following requirements:
- 3 fill years only - 2010,2011,2012
- xlabels - %b%y format; sorted on month-year sequence; las2 positioned (vertical)
- facet_grid by year with only that year's xlabels and bars in the appropriate facet-grid