Re: facet_grid and facet_wrap in same plot

372 views
Skip to first unread message

Felipe Carrillo

unread,
Aug 31, 2012, 3:50:52 PM8/31/12
to rb, ggp...@googlegroups.com
Here is one way,
You can render both plots and then use grid.arrange to put them together
 
require(ggplot2)
require(plyr)
library(reshape2)
ret <- rnorm(20)/100
risk <- apply(matrix(rnorm(20*20)/100, ncol =20), 2, sd)
testdata <- data.frame(cbind(ret, risk))
testdata$fact <- c(rep('StockA', 10), rep('StockB', 10))
testdata$date <- as.character(seq.Date(from = as.Date('2009-01-01'), by = 'day', length.out= 10) )
m <- melt(testdata, id = c('date', 'fact'))
m
d <- ggplot(m, aes(x = date, y= value)) + geom_line()  + facet_grid(variable ~ .)
d
dd <- d + facet_wrap(~fact)
dd
library(gridExtra)
grid.arrange(d,dd)
 
Felipe D. Carrillo
Supervisory Fishery Biologist
Department of the Interior
US Fish & Wildlife Service
California, USA

From: rb <reenas...@gmail.com>
To: ggp...@googlegroups.com
Sent: Friday, August 31, 2012 11:32 AM
Subject: facet_grid and facet_wrap in same plot

Hello,
 
I am trying to use facet_grid and facet_wrap in same plot but unable to do it succesfully. I have two stocks and for each stock I want to plot daily return and daily risk measure (both time series). I do a facet_grid first to separate the risk and return of each stock and then apply facet wrap to separate the stocks. However it does not work. Any suggestions?
 
ret <- rnorm(20)/100
risk <- apply(matrix(rnorm(20*20)/100, ncol =20), 2, stdev)
testdata <- data.frame(cbind(ret, risk))
testdata$fact <- c(rep('StockA', 10), rep('StockB', 10))
testdata$date <- as.character(seq.Date(from = as.Date('2009-01-01'), by = 'day', length.out= 10) )

m <- melt(testdata, id = c('date', 'fact'))
d <- ggplot(m, aes(x = datestamp, y= value)) + geom_line()  + facet_grid(variable ~ .)  
d
d + facet_wrap(~fact)
 
Thanks so much for your help!
RB
--
You received this message because you are subscribed to the ggplot2 mailing list.
Please provide a reproducible example: https://github.com/hadley/devtools/wiki/Reproducibility
 
To post: email ggp...@googlegroups.com
To unsubscribe: email ggplot2+u...@googlegroups.com
More options: http://groups.google.com/group/ggplot2


rb

unread,
Sep 4, 2012, 12:32:18 PM9/4/12
to ggp...@googlegroups.com, rb, Felipe Carrillo
Thanks Felipe. gridExtra is a convenient package which I was not aware of. However this doesn't answer my question. I want to be able to plot for each stock a grid of ret and risk (in the form of variable d in the code). So two plots of type d for each stock. Hope this makes sense.
Reply all
Reply to author
Forward
0 new messages