'Using ggplot in a function
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
Solution 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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Matt Cowgill |
