1

I am trying to create a function in r using ggplot. This is my code so far:

breakchart<-function(df,x,y) {
  ggplot(df,aes( {{x}} ,{{y}}))  + geom_point() +
    ylim(-20,20) + xlim(-20,20) + 
    geom_hline(yintercept = 0) +
    geom_vline(xintercept = 0) + 
    ggtitle(" Break Chart") 

This has worked. However, I want to add a color aesthetic to my graphing function. EXAMPLE: ggplot(df,aes( x , y, color = ??)) + geom_point()

I am not sure how to do this without causing an error. Does anybody have an idea how to do this? Thanks

2
  • 3
    Does it not work if you just use the same approach as for x and y? ie, aes({{ x }}, {{ y }}, color = {{ color }})? What have you tried, and what error are you seeing? Commented Mar 10, 2022 at 3:37
  • Yes, it worked- had to adjust something small in the code when I was defining the function. Thanks Commented Mar 15, 2022 at 0:29

1 Answer 1

1

The approach you've already taken works for me.

library(ggplot2)

breakchart<-function(df, 
                     x,
                     y, 
                     colour, 
                     ylim = c(-20, 20), 
                     xlim = c(-20, 20),
                     title = "Break chart") {
  ggplot(df,
         aes(x = {{x}},
             y = {{y}},
             colour = {{colour}})
         )  + 
    geom_point() +
    ylim(ylim) + xlim(xlim) + 
    geom_hline(yintercept = 0) +
    geom_vline(xintercept = 0) + 
    ggtitle(title) 
}

breakchart(mtcars, wt, mpg, col = factor(cyl))
#> Warning: Removed 14 rows containing missing values (geom_point).

Created on 2022-03-10 by the reprex package (v2.0.1)

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, just had to adjust something small in the code while defining the function.
If this answers your question, please accept the answer (mark it as accepted)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.