Variable in group_by and ggplot

I have this code snippet:

group_by(Session,Risk) %>%
plot1 <- ggplot(DF, aes(x = Session, y = n, color = Risk)) + 
  theme(axis.text.x = element_text(angle = 90), legend.position="bottom", 
        legend.text = element_text(size=10))  + 
  geom_point() + geom_line(aes(group = Risk), lty = 1)

I am trying to replace "Risk" with a variable so that if I have to change it I only need to do it once instead of changing all. So I try adding this:

var1 <- "Risk" and modify the codes to be like this:

group_by(Session,var1) %>%
plot1 <- ggplot(DF, aes(x = Session, y = n, color = var1)) + 
  theme(axis.text.x = element_text(angle = 90), legend.position="bottom", 
        legend.text = element_text(size=10))  + 
  geom_point() + geom_line(aes(group = var1), lty = 1)

but when I run the script, the graph is not showing the correct plot anymore, instead of showing multiple line plot, the is only one line with wrong values.

Please help.

Can you supply some sample data? See FAQ: How to do a minimal reproducible example ( reprex ) for beginners

Define a function, see this example with the iris dataset:

library(tidyverse)

custom_function <- function(variable) {
    group_by(iris, {{variable}}) %>%
        ggplot(aes(x = Sepal.Length, y = Sepal.Width, color = {{variable}})) + 
            theme(axis.text.x = element_text(angle = 90), legend.position="bottom", 
                  legend.text = element_text(size=10))  + 
            geom_point() + geom_line(aes(group = {{variable}}), lty = 1)
}

custom_function(Species)

Created on 2021-02-09 by the reprex package (v1.0.0)

If you need more specific help, please provide a proper REPRoducible EXample (reprex) illustrating your issue.

1 Like

Thank you for the tips. I have tried it but I got into another issue with my function. However, let me try working on it first and will be back if it is necessary.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.