ggplot2 - faceting monthly data by year in r - months with no data appear -


i'm trying create grouped bar chart of monthly data, aggregated daily data, on multiple years. have accomplished wanted x-axis faceting, using faceting way apply secondary sort (on year , month). i've faceted year, ggplot showing months - when there's no data. wasting space , actual data set has years of data , want add labels, space issue.

how can accomplish without wasted space? there way add secondary sort (year,month) on x-axis without faceting?

ggplot example

# create data set date = seq(as.date("2014-05-01"),as.date("2015-05-10"), "day") revenue = runif(375, min = 0, max = 200) cost = runif(375, min = 0, max = 100) df = data.frame(date,revenue,cost) head(df)  # adding month , year column, aggregating monthly revenue , cost  library(plyr) df$month <- month(df$date, label=true)  df$year <- year(df$date)  df <- as.data.frame(ddply(df, .(month,year), numcolwise(sum)))  # melting data 'grouped chart' in ggplot library(reshape) df <-melt(df, id = c("month","year"))  #create chart library(ggplot2) g <-ggplot(df, aes(x=month, y=value, fill=variable))  g + geom_bar(stat="identity", position="dodge") + facet_wrap(~ year) 

i feel there's more elegant way within ggplot. right?

the key use scale = "free" in facet_wrap(). following code (with revision), you'll see graphic below.

set.seed(222) date = seq(as.date("2014-05-01"),as.date("2015-05-10"), "day") revenue = runif(375, min = 0, max = 200) cost = runif(375, min = 0, max = 100) mydf = data.frame(date,revenue,cost)  mydf$month <- month(mydf$date, label=true)  mydf$year <- year(mydf$date)  mydf2 <- as.data.frame(ddply(mydf, .(month,year), numcolwise(sum)))  mydf3 <- melt(mydf2, id = c("month","year"))  ggplot(mydf3, aes(x=month, y=value, fill=variable)) + geom_bar(stat = "identity", position = "dodge") + facet_wrap(~ year, scale = "free") 

enter image description here


Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -