[R] use ggplot in a function to which a column name is given
jiho
jo.irisson at gmail.com
Thu Dec 13 10:45:32 CET 2007
Hi everyone, Hi ggplot users in particular,
ggplot makes it very easy to plot things given their names when you
use it interactively (and therefore can provide the names of the
columns).
qplot(x,foo,data=A) where A has columns (x,y,foo,bar) for example
but I would like to use this from inside a function to which the name
of the column is given. I cannot find an elegant way to make this
work. Here are my attempts:
#------------------------------------------------------------
library(ggplot2)
A = data.frame(x=rep(1:10,10), y=rep(1:10,each=10), u=runif(100),
v=rnorm(100))
# goal: extract values for y<=5 and plot them, either for u or v
foo1 <- function(uv="u")
{
# solution 1: do not use the data argument at all
# (forces the use of qplot, could be more elegant)
B = A[A$y<=5,]
qplot(B$x, B$y, fill=B[[uv]], geom="tile")
}
foo2 <- function(uv="u")
{
# solution 2: extract and rename the colums, then use the data argument
# (enables ggplot but could be shorter)
B = A[A$y<=5,c("x","y",uv)]
names(B)[3] = "value"
# rem: cannot use rename since rename(B,c(uv="value")) would not work
qplot(x, y, fill=value, data=B, geom="tile")
# or
# ggplot(B,aes(x=x,y=y,fill=value)) + geom_tile()
}
foo3 <- function(uv="u")
{
# solution 3: use the data argument and perform the extraction
directly in it
# (elegant and powerful but can't make it work)
ggplot(A[A$y<=5,c("x","y",uv)],aes(x=x,y=y,fill=???)) + geom_tile()
# or
ggplot(A[A$y<=5,],aes(x=x,y=y,fill=???)) + geom_tile()
# or ...
}
print(foo1("u"))
print(foo1("v"))
print(foo2("u"))
print(foo3("u"))
#------------------------------------------------------------
Any help in making foo3 work would be appreciated. Thanks in advance
for your expertise.
JiHO
---
http://jo.irisson.free.fr/
More information about the R-help
mailing list