Re: Plot >1 variable in dataframe

36 views
Skip to first unread message

Brandon Hurr

unread,
Nov 10, 2012, 8:46:24 AM11/10/12
to Ross, ggplot2
This post from Baptiste seems to be right up your alley. 



On Sat, Nov 10, 2012 at 7:19 AM, Ross <ross...@googlemail.com> wrote:
The following code plots a boxplot without any problems:

library(ggplot2)
ggplot(aes(y=disp, x = as.factor(cyl)), data = mtcars) + geom_boxplot()

However, it doesn't work if I try to plot >1 column:

library(plyr)
llply(mtcars[,9:11], function(x) ggplot(aes(y=x, x = as.factor(cyl)), data = mtcars) + geom_boxplot())

Any ideas what I''m doing wrong?

--
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

Ben Bond-Lamberty

unread,
Nov 10, 2012, 8:47:16 AM11/10/12
to ggp...@googlegroups.com
I'm pretty confused as to what you're trying to do. mtcars is a data
frame, and ggplot works best with data frames, so why are you using
llply? In any event, you're operating on columns 9:11 of mtcars, which
doesn't include the 'cyl' column, which is a problem right there.

Personally, to plot multiple columns I'd do something like this:

library( reshape )
mtcars1 <- mtcars[ c( 2, 9:11 ) ]
mtcars1 <- melt( mtcars, id.vars="cyl" )
ggplot( mtcars1, aes( cyl, value ) ) + geom_boxplot() + facet_grid(
variable~., scales="free_y" )

Ben
Message has been deleted

Ross

unread,
Nov 11, 2012, 9:38:10 AM11/11/12
to ggp...@googlegroups.com
Heres's same thing done with base plotting functions:

llply(mtcars[,9:11], function(myplot) plot(myplot, x=as.factor(mtcars$cyl)))

Would be interesting to know why ggplot2 didnt work.

Ross

baptiste auguie

unread,
Nov 11, 2012, 1:49:22 PM11/11/12
to Ross, ggp...@googlegroups.com
it's typically a job for aes_string,

 pl = llply(names(mtcars[,9:11]), function(n) ggplot(mtcars, aes_string(x='cyl', y=n)) + geom_path())
do.call(gridExtra::grid.arrange, pl)

HTH,

b,


--
Reply all
Reply to author
Forward
0 new messages