[R] How to stratify data with multiple group simultaneously with R ggplot2?
Rui Barradas
ru|pb@rr@d@@ @end|ng |rom @@po@pt
Sun Jun 8 18:03:31 CEST 2025
Às 07:21 de 08/06/2025, Luigi Marongiu escreveu:
> 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 using 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.
Hello,
You can use the 4th variable to define facets. Like this?
ggplot(df, aes(x=x, y=y, colour=w)) +
geom_line(linewidth=2) +
facet_wrap(~ z, scales = "free_x") +
ggtitle("A+B")
Hope this helps,
Rui Barradas
--
Este e-mail foi analisado pelo software antivírus AVG para verificar a presença de vírus.
www.avg.com
More information about the R-help
mailing list