I have a plot, that i repeat numerous times, just with different variables, so i want to make it into a function:
getSecPlot <- function(data, xvar, yvar, yvarsec, groupvar, ...){
sec_plot <- ggplot(data, aes_string (x = xvar, group = groupvar)) +
geom_col(aes_string(y = yvar, fill = groupvar), position = "dodge") +
geom_line(aes_string(y = yvarsec), color = groupvar)
}
test <- getSecPlot(freqSevDataAge, xvar = get("agegroup"), yvar = "severity",
yvarsec = "frequency", groupvar = "gender")
I get an error:
Unknown colour name: gender
I assume that this is because the color is evaluated as color = "gender"
because of the aes_string
.
How can this be fixed? I tries using enquo()
and !!
, but it has not worked. Any tips?
also related to this, i want to scale the yvarsec
by a parameter. I have done thee following:
getSecPlot <- function(data, xvar, yvar, yvarsec, groupvar, ...){
param <- max(as.numeric(freqSevData$yvar), na.rm = TRUE)/max(as.numeric(freqSevData$yvarsec), na.rm = TRUE)
sec_plot <- ggplot(data, aes_string (x = xvar, group = groupvar)) +
geom_col(aes_string(y = yvar, fill = groupvar), position = "dodge") +
geom_line(aes_string(y = as.numeric(yvarsec) * as.numeric(param)), color = groupvar) +
theme_pubclean()
}
which return a plot without the line. Again, i believe this is related to the NSE and aes_string
.
without the as.numeric
i get an error:
Error in yvarsec * param : non-numeric argument to binary operator
Proposed solution as by @linog
getSecPlot <- function(data, xvar, yvar, yvarsec, groupvar, ...){
df[,"param"] <- max(as.numeric(data[, yvar]), na.rm = TRUE)/max(as.numeric(data[, yvarsec]), na.rm = TRUE)
df[,"param"] <- df[,"param"]* df[, yvarsec]
sec_plot <- ggplot(data, aes_string (x = xvar, group = groupvar)) +
geom_col(aes_string(y = yvar, fill = groupvar), position = "dodge") +
geom_line(aes_string(y = "param", color = groupvar)) +
theme_pubclean()
}
test <- getSecPlot(freqSevDataAge, xvar = get("agegroup"),
yvar = "severity", yvarsec = "frequency", groupvar = "gender")
test