How to plot lines selected by indices from dataframe on the same graph with ggplot and purrr?

Viewed 112

I have list of indices

l <- list(a = sample(1:nrow(mpg), 10), b = sample(1:nrow(mpg), 15), c = sample(1:nrow(mpg), 10),
          d = sample(1:nrow(mpg), 12), e = sample(1:nrow(mpg), 17))

I try to plot lines selected by indices stored in l on the same graph. Is it possible to compactify next expression with purrr?

library(tidyverse)
ggplot() +
  geom_line(data = mpg[l$a, ], aes(x = displ, y = cty), color = RColorBrewer::brewer.pal(5, "Set2")[1]) +
  geom_line(data = mpg[l$b, ], aes(x = displ, y = cty), color = RColorBrewer::brewer.pal(5, "Set2")[2]) +
  geom_line(data = mpg[l$c, ], aes(x = displ, y = cty), color = RColorBrewer::brewer.pal(5, "Set2")[3]) +
  geom_line(data = mpg[l$d, ], aes(x = displ, y = cty), color = RColorBrewer::brewer.pal(5, "Set2")[4]) +
  geom_line(data = mpg[l$e, ], aes(x = displ, y = cty), color = RColorBrewer::brewer.pal(5, "Set2")[5])
3 Answers

You can build a new dataset to plot the data:

df = numeric() #Empty starting point
for(i in 1:length(l)){
  df = rbind(df, cbind(mpg[l[[i]],], name=names(l)[i]))}
#Rbind the last iteration with the mpg on the indexes + a column with the name of the index

ggplot(df, aes(x=displ, y=cty, color=name)) +
  geom_line()

You can change the color pallete with a scale_color_brewer().

Output:

enter image description here

library(tidyverse)

l <- list(a = sample(1:nrow(mpg), 10), b = sample(1:nrow(mpg), 10), c = sample(1:nrow(mpg), 10),
          d = sample(1:nrow(mpg), 10), e = sample(1:nrow(mpg), 10))

# Generate a list of ggplot layers to add to the final plot
layer_list <- map2(.x = l,
                   .y = seq_along(l),
                   .f = ~ geom_line(data = mpg[.x, ], aes(x = displ, y = cty),
                                    color = RColorBrewer::brewer.pal(5, "Set2")[.y]))

# Build the final plot
ggplot(data = mpg) +
  layer_list 

It's a matter of calling out the relevant rows of the data frame, and providing a column with the corresponding name:

library(tidyverse)
data(mpg)

mpg[unlist(l),] %>%
mutate(data =  rep(names(l),lengths(l))) %>%
ggplot() +
geom_line(aes(x = displ, y = cty,color = data)) +
scale_color_manual(values=RColorBrewer::brewer.pal(5, "Set2"))

enter image description here

Related