Reputation: 845
I have a list of values and a list of ggplots. I would like to attach the values from the list on to the ggplots. Is there a good way to do that?
Here's what I have for the list of ggplots:
p.list <- lapply(sort(unique(ind_steps$AnimalID)), function(i){
ggplot(ind_steps[ind_steps$AnimalID == i,], aes(x = t2, y = NSD)) +
geom_line() + theme_bw() +
theme(axis.text.x = element_text(angle = 90)) +
scale_x_datetime(date_breaks = '10 days', date_labels = '%y%j') +
facet_grid( ~ AnimalID, scales = "free") +
scale_colour_manual(values=hcl(seq(15,365,length.out=4)[match(i, sort(unique(ind_steps$AnimalID)))], 100, 65))
})
Assuming I have another list the same length as this one, and each one has a single value in each list.
I want to pair the ggplots with the list of values, and have the values show up in each respective plot. My expected output would be to have each value from the list of values be on each respective plot within the list of plots.
Upvotes: 0
Views: 69
Reputation: 2584
Since you don't provide any example data here I put an example with the iris
built-in dataset. You can add values to plots with geom_text
or geom_label
(if I well understood what you want). For example, here we add the R^2 values to all the plot in a list:
library(ggplot2)
data(iris)
rsq <- lapply(1:length(unique(iris$Species)), function(i) {
cor(iris[iris$Species == unique(iris$Species)[i], "Sepal.Length"], iris[iris$Species == unique(iris$Species)[i], "Petal.Length"])^2
})
p.list <- lapply(1:length(unique(iris$Species)), function(i) {
ggplot(iris[iris$Species == unique(iris$Species)[i], ], aes(x = Sepal.Length, y = Petal.Length)) +
geom_point() + theme_bw()+
geom_text(aes(x=min(Sepal.Length),y=max(Petal.Length),label=paste0("R= ",round(rsq[[i]],2))))
})
library(gridExtra)
grid.arrange(p.list[[1]],p.list[[2]],p.list[[3]],nrow=3)
which return :
Upvotes: 1