R 将多个参数传递给由ggplot组成的函数
嗨,我有这段代码,我用了一次又一次R 将多个参数传递给由ggplot组成的函数,r,ggplot2,R,Ggplot2,嗨,我有这段代码,我用了一次又一次 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
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<-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")
}
请注意,现在您正在传递data.frame本身,而不是作为字符串传递data.frame的名称。由于要将列名作为字符串传递,因此需要将aes\u string
中的所有内容作为字符串传递
如果确实希望将data.frame名称作为字符串传递,可以将第一个ggplot()
调用更改为
ggplot(get(arg1), aes_string(x=arg2, y=arg3, colour ="id")) +
首先,您需要有
p我现在得到这个错误:aes_字符串中的错误(x=arg2,y=arg3,color=id):找不到对象“id”调用自:aes_字符串(x=arg2,y=arg3,color=id)浏览[1]>将id放在引号中。你也可以提供一些数据,这会有帮助嗨,为什么id应该在引号里?它来自数据帧。不是参数。my.function(arg1=foo1,arg2='log(area)',arg3='log(fd))
适合我。您需要'id'
,因为您使用的是aes\u字符串。我从来没有使用过ggsave作为图层,所以我不能对此发表评论。运行函数后返回绘图并保存:p您好,谢谢。一个简单的问题。我如何传递say xlab的参数?我想发送一个名称。@GeekunaMatata将arg4作为参数添加到您的函数中,然后将xlab('John')+
更改为xlab(arg4)+
您也可以看一下吗?谢谢
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)')
ggplot(get(arg1), aes_string(x=arg2, y=arg3, colour ="id")) +