就像joran提到的那样,我猜......但是:
您可以做两件事之一,编辑 ggplot2 对象(坏主意)或将绘图包装在一个函数中。
让我们使用以下数据和绘图调用:
dat <- data.frame(x=1:10, y=10:1, z=1, a=letters[1:2], b=letters[3:4])
# p <- ggplot(dat, aes_string(x=xvar, y=yvar, color=colorvar)) + geom_point()
请注意,我使用aes_string
了所以我可以传递变量而不是列名。
xvar <- 'y'
yvar <- 'z'
colorvar <- 'a'
p <- ggplot(dat, aes_string(x=xvar, y=yvar, color=colorvar)) + geom_point()
的结构p
如下,我将把它留给你来整理编辑它。相反,将 ggplot 包装在一个函数中:
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"