2

I looked through many answers, but still have problems programming a function for a plot in ggplot2. Here is a sample dataset:

 d<-data.frame(replicate(2,sample(0:9,1000,rep=TRUE)))
 colnames(d)<-c("fertilizer","yield")

Now I write the following function - I only want to give x and y to the function:

test <- function(explanatory,response)
{
plot<- ggplot(d, aes(x =explanatory, y=response)) +
  geom_point()+ 
  ggtitle("Correlation between Fertilizer and Yield")  +
  theme(plot.title = element_text(size = 10, face = "bold"))+
  geom_smooth(method=lm, se=FALSE) + 
  annotate("text", x=800, y=20, size=5,label= cor6) 
plot
}

When I call this function with this,

test("fertilizer","yield")

I get a graph without any scatter points like this:

Graph I get

Could anybody help me? I really want to learn to write functions in R.

Olympia
  • 457
  • 8
  • 19
  • 1
    See also these https://stackoverflow.com/a/50726130/786542 & https://stackoverflow.com/a/50930640/786542 – Tung Dec 04 '18 at 16:10

3 Answers3

4

Use aes_string instead of aes. It should work. Worked for me :)

Note: Remove the quotes around your arguments in the function definition. Also your cor6 should be in quotes. See below

test <- function(explanatory,response)
{
plot<- ggplot(d, aes_string(x =explanatory, y=response)) +
  geom_point()+ 
  ggtitle("Correlation between Fertilizer and Yield")  +
  theme(plot.title = element_text(size = 10, face = "bold"))+
  geom_smooth(method=lm, se=FALSE) + 
  annotate("text", x=800, y=20, size=5,label= "cor6") 
plot
 }
TheDataGuy
  • 371
  • 1
  • 6
2

If you use enquo and !!, the quotes aren't needed.

 test <- function(explanatory,response)
{
  explanatory <- enquo(explanatory)
  response <- enquo(response)
  plot <- 
    ggplot(d, aes(x = !!explanatory, y = !!response)) +
      geom_point()+ 
      ggtitle("Correlation between Fertilizer and Yield")  +
      theme(plot.title = element_text(size = 10, face = "bold"))+
      geom_smooth(method=lm, se=FALSE) + 
      annotate("text", x=800, y=20, size=5,label= 'cor6') 
  plot
 }

 test(fertilizer, yield)
IceCreamToucan
  • 28,083
  • 2
  • 22
  • 38
1

Change label= cor6 tp label= "cor6"

Also in:

annotate("text", x=800, y=20, size=5,label= cor6) 

x, y change the range of your plot, your values go from 1 to 9, remove them or set according to your variables range

Treizh
  • 322
  • 5
  • 12