I have a simple code that creates a combined barplot and line plot with two axes. I wanted to make this code dynamic so that I can pass the columns to plot as parameters of a function. Here is the code outside the function,it works fine:
data <- data.frame(group = LETTERS[1:5], # Create example data
sample = c(1000, 800, 1200, 900, 800),
responses1 = c(0.6, 0.9, 0.9, 0.5, 0.8),
responses2 = c(0.2, 0.4, 0.7, 0.1, 0.3)
)
ggp1 <- ggplot(data) +
geom_bar(aes(group, sample), stat = "identity") +
geom_line(aes(group, responses * max(sample), group = 1),
col = "#1b98e0", lwd = 3) +
scale_y_continuous(sec.axis = sec_axis(~ . / max(data$sample)))
ggp1
Now when trying to put it in a function it becomes challenging a little bit for me:
plot_func <- function(var1, var2) {
ggp1 <- ggplot(data) +
geom_bar(aes(group, var1), stat = "identity") +
geom_line(aes(group, var2 * max(var1), group = 1),
col = "#1b98e0", lwd = 3) +
scale_y_continuous(sec.axis = sec_axis(~ . / max(data[[var1]])))
ggp1
}
!!sym(x)or the newer{{x}}.plot_func()? It should beplot_func(responses1)responsesis not defined anywhere.