1

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.

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Hi, any suggestions for saving plots on the fly? Thanks
0

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)
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.