Environment: Win 7 HP, R v2.15.1
What I wish to get to:
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:
To answer your 3 points:
The following code will do it:
MySample$date <- as.Date(MySample$x, "%m-%d-%y")
MySample$year <- year(MySample$date)
ggplot(MySample, aes(date, y, fill = year)) +
geom_bar(y=y,stat="identity") +
facet_grid(. ~ year, scales = "free") +
scale_x_date(labels = date_format("%b/%y")) +
scale_fill_gradient(breaks=unique(MySample$year))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With