嗨,我有这段代码,我一次又一次地使用
ggplot(foo1, aes(x=log(area), y=log(fd), colour = id)) +
geom_point()+
scale_color_manual(name = "Regions",values=cols)+
xlab('John')+
ylab('Peter')+
ggtitle("xyz")+
ggsave("x.png")
我写了这个:
my.function<-function(arg1,arg2,arg3){
ggplot(arg1, aes_string(x=arg2, y=arg3, colour = id)) +
geom_point()+
scale_color_manual(name = "Regions",values=cols)+
xlab('John')+
ylab('Peter')+
ggtitle("xyz")+
ggsave("x.png")
}
我这样称呼
my.function(arg1='foo1',arg2='log(area)',arg3='log(fd)')
但它不起作用。我以前从未写过函数。我想在每个函数调用中保存图形。你能帮忙吗?
dput(head(foo1,4))
structure(list(id = structure(c(1L, 1L, 1L, 1L), .Label = c("dfa",
"dfb", "cfa", "csb", "bsk"), class = "factor"), lon = c(-70.978611,
-70.978611, -70.945278, -70.945278), lat = c(42.220833, 42.220833,
42.190278, 42.190278), peakq = c(14.7531, 17.3865, 3.3414, 2.7751
), area = c(74.3327, 74.3327, 11.6549, 11.6549), fd = c(29, 54.75,
23, 1), tp = c(14.25, 19.75, 13.5, 0.5), rt = c(14.75, 35, 9.5,
0.5), bl = c(15485.3, 15485.3, 8242.64, 8242.64), el = c(0.643551,
0.643551, 0.474219, 0.474219), k = c(0.325279, 0.325279, 0.176624,
0.176624), r = c(81.947, 81.947, 38.7003, 38.7003), si = c(0.0037157,
0.0037157, -9999, -9999), rr = c(0.00529193, 0.00529193, 0.00469513,
0.00469513)), .Names = c("id", "lon", "lat", "peakq", "area",
"fd", "tp", "rt", "bl", "el", "k", "r", "si", "rr"), row.names = c(NA,
4L), class = "data.frame")
答案 0 :(得分:2)
怎么样
my.function<-function(arg1,arg2,arg3){
ggplot(arg1, aes_string(x=arg2, y=arg3, colour ="id")) +
geom_point()+
scale_color_manual(name = "Regions",values=cols)+
xlab('John')+
ylab('Peter')+
ggtitle("xyz")+
ggsave("x.png")
}
然后用
来调用它my.function(arg1=foo1,arg2='log(area)',arg3='log(fd)')
请注意,现在您将传递data.frame本身,而不是data.frame的名称作为字符串传递。由于您将列名称作为字符串传递,因此您需要将aes_string
中的所有内容作为字符串传递。
如果您确实想将data.frame名称作为字符串传递,可以将第一个ggplot()
调用更改为
ggplot(get(arg1), aes_string(x=arg2, y=arg3, colour ="id")) +