简体   繁体   中英

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:

我得到的图

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

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
 }

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM