carlite71
carlite71

Reputation: 413

Making multiple plots from a list of data frames - with colors (ggplot2)

I'm trying to make 9 line graphs in ggplot2, each one using data from each of the data frame in a list (called "my_list").

I found a neat solution here: Making multiple plots from a list of data frames

but I need an extra twist: the lines on each of the plots need to be of different colors.

EDIT - I figured it out, see answer below.

Upvotes: 1

Views: 1758

Answers (2)

baptiste
baptiste

Reputation: 77116

I think it's easier to define a wrap-up function,

dl = replicate(5, data.frame(x=1:10, y=rnorm(10)), simplify = FALSE)

plot_fun = function(d, col) {
       ggplot(d, aes_string(x="x",y="y")) + geom_line(col=col) +
         theme()
}

pl = mapply(plot_fun, d = dl, col = palette()[1:5], SIMPLIFY=FALSE)

# interactive use
gridExtra::grid.arrange(grobs=pl)

## save to a device
ggsave("plotstosave.pdf", gridExtra::arrangeGrob(grobs=pl))

enter image description here

Upvotes: 2

carlite71
carlite71

Reputation: 413

I managed to figure it out, thought I'd share what I've learned.

# first create a vector with the colors you want
colors = c("red", "blue", "green", "purple", "cyan", "orange", "teal", "pink", "maroon") 

# then loop through the colors in geom_line (as opposed to doing it in the ggplot aes, that gave me lines of the same color every time).

for(i in 1:length(my_list))
{
    df1 = as.data.frame(my_list[[i]])
    plotdf1 <- ggplot(df1, aes(x=x, y=y)) +
               geom_line(size=1,color=colors[i])
    print(plotdf1)
}

Upvotes: 0

Related Questions