You can use group=interaction(w,z)... but in my experience that gets confusing for the poor person trying to make sense of the plot. It is better to use color=w, linetype=z or use facets for one of the grouping variables.
On June 7, 2025 11:21:32 PM PDT, Luigi Marongiu <marongiu.lu...@gmail.com> wrote: >I would like to plot multivariate data with ggplot2. I have multiple >groups that I need to account for: I have the `x` and `y` values, but >the data must be stratified also by `w` and `z`. I can group by either >`w` or `z`, but how can I group for both simultaneously? >In essence, in the example below, the legend should have two columns >(A and B) and five rows (which are already there since the data is >stratified by w). There should be 10 colors. >How can I do that? >Thank you > >>>>>>> >``` >df = data.frame(x = c(rep(1,5), rep(2,5), rep(3,5), rep(4,5)), > w = rep(letters[1:5],4), > z = c(rep(LETTERS[1],10), rep(LETTERS[2],10)), > y = rnorm(20), > stringsAsFactors = FALSE) >library(ggplot2) >ggplot(df, aes(x=x, y=y, colour=w, group=w)) + > geom_line(linewidth=2) + > ggtitle("A+B") >ggplot(df[df$z=="A",], aes(x=x, y=y, colour=w, group=w)) + > geom_line(linewidth=2) + > ggtitle("A") >ggplot(df[df$z=="B",], aes(x=x, y=y, colour=w, group=w)) + > geom_line(linewidth=2) + > ggtitle("B") >``` > >______________________________________________ >R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see >https://stat.ethz.ch/mailman/listinfo/r-help >PLEASE do read the posting guide https://www.R-project.org/posting-guide.html >and provide commented, minimal, self-contained, reproducible code. -- Sent from my phone. Please excuse my brevity. ______________________________________________ R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide https://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.