Reputation: 1439
Hi I have this piece of code that I use again and again
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")
And I wrote this:
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")
}
I am calling this way
my.function(arg1='foo1',arg2='log(area)',arg3='log(fd)')
But it doesn't work. I have never written functions before. I want to save the figure in every function call. Could you please help?
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")
Upvotes: 0
Views: 1152
Reputation: 206232
How about
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")
}
and you call it with
my.function(arg1=foo1,arg2='log(area)',arg3='log(fd)')
Note that now you're passing the data.frame itself, not the name of the data.frame as a string. And since you're passing the column names as strings, you need to pass everything in aes_string
as strings.
If you really want to pass the data.frame names as a string, you can change the first ggplot()
call to
ggplot(get(arg1), aes_string(x=arg2, y=arg3, colour ="id")) +
Upvotes: 2