Create graphs by group using ggplot in R
To achieve your desired result
- Split your dataframe by
group
using e.g.split
- Use
lapply
to loop over the list of splitted data frames to create your plots or if you want to add the group labels to the title you could loop overnames(df_split)
.
Note: I converted the id
variable to factor. Also, you have to map id
on the group aesthetic to get lines per group. However, as your x variable is a numeric there is actually no need for the group
aesthetic.
library(ggplot2)
df_split <- split(df, df$group)
lapply(df_split, function(df) {
ggplot(df, aes(x = x, y = y, group = id, color = factor(id))) +
geom_line()
})
lapply(names(df_split), function(i) {
ggplot(df_split[[i]], aes(x = x, y = y, group = id, color = factor(id))) +
geom_line() +
labs(title = paste("group =", i))
})
#> [[1]]
#>
#> [[2]]
And even I if would recommend to use lapply
the same could be achieved using a for
loop like so:
for (i in names(df_split)) {
print(
ggplot(df_split[[i]], aes(x = x, y = y, group = id, color = factor(id))) +
geom_line() +
labs(title = paste("group =", i))
)
}