As joran mentions, I guess ... but:
you can do one of two things, edit the ggplot2 object (a bad idea) or wrap a graph in a function.
allows you to use the following data and graph:
dat <- data.frame(x=1:10, y=10:1, z=1, a=letters[1:2], b=letters[3:4])
Notice that I used aes_string , so I can pass variables, not column names.
xvar <- 'y' yvar <- 'z' colorvar <- 'a' p <- ggplot(dat, aes_string(x=xvar, y=yvar, color=colorvar)) + geom_point()
Below is the p structure, and I will leave it to you to sort it. Instead, wrap ggplot in a function:
plotfun <- function(DF, xvar, yvar, colorvar) { ggplot(DF, aes_string(x=xvar, y=yvar, color=colorvar)) + geom_point() } p <- plotfun(dat, 'z', 'x', 'a') p
str(p) List of 8 $ data :'data.frame': 10 obs. of 5 variables: ..$ x: int [1:10] 1 2 3 4 5 6 7 8 9 10 ..$ y: int [1:10] 10 9 8 7 6 5 4 3 2 1 ..$ z: num [1:10] 1 1 1 1 1 1 1 1 1 1 ..$ a: chr [1:10] "a" "b" "a" "b" ... ..$ b: chr [1:10] "c" "d" "c" "d" ... $ layers :List of 1 ..$ :Classes 'proto', 'environment' <environment: 0x34d5628> $ scales :Reference class 'Scales' [package "ggplot2"] with 1 fields ..$ scales: list() ..and 20 methods, of which 9 are possibly relevant: .. add, clone, find, get_scales, has_scale, initialize, input, n, non_position_scales $ mapping :List of 3 ..$ x : symbol y ..$ y : symbol x ..$ colour: symbol a $ options :List of 1 ..$ labels:List of 3 .. ..$ x : chr "z" .. ..$ y : chr "x" .. ..$ colour: chr "a" $ coordinates:List of 1 ..$ limits:List of 2 .. ..$ x: NULL .. ..$ y: NULL ..- attr(*, "class")= chr [1:2] "cartesian" "coord" $ facet :List of 1 ..$ shrink: logi TRUE ..- attr(*, "class")= chr [1:2] "null" "facet" $ plot_env :<environment: R_GlobalEnv> - attr(*, "class")= chr "ggplot"