[R] use ggplot in a function to which a column name is given

From: jiho <jo.irisson_at_gmail.com>
Date: Thu, 13 Dec 2007 10:45:32 +0100

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:



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



Any help in making foo3 work would be appreciated. Thanks in advance for your expertise.



R-help_at_r-project.org mailing list
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
Received on Thu 13 Dec 2007 - 09:49:44 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Thu 13 Dec 2007 - 15:30:19 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.