[R] How to stratify data with multiple group simultaneously with R ggplot2?
Luigi Marongiu
m@rong|u@|u|g| @end|ng |rom gm@||@com
Sun Jun 8 08:21:32 CEST 2025
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")
```
More information about the R-help
mailing list