Olympia
Olympia

Reputation: 537

How do I write a function for a plot in ggplot2 using correctly aes?

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.

Upvotes: 2

Views: 222

Answers (3)

IceCreamToucan
IceCreamToucan

Reputation: 28675

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)

Upvotes: 2

TheDataGuy
TheDataGuy

Reputation: 371

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
 }

Upvotes: 4

Treizh
Treizh

Reputation: 322

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

Upvotes: 1

Related Questions