Home > Enterprise >  Using paste() during lapply with ggplot and two different data sources
Using paste() during lapply with ggplot and two different data sources

Time:10-05

Consider a list of ggplots:

list1 <- vector("list", 7)
names(list1) <- LETTERS[1:7]
list1 <- lapply(list1, function(x) {x <- ggplot(data.frame())   geom_point()   xlim(0, 10)   ylim(0, 100);x})

I could use

list1 <- lapply(list1, function(x) {x <- x   annotate("text", label="some text", x=4, y=4)})

to annotate some text into each plot and plot the whole list with

lapply(names(list1), 
       function(x) ggsave(filename=paste(x,".jpg",sep=""), plot=list1[[x]]))

but the text i want to annotate into each plot is variable and stored in another vector:

somevec <- runif(7)

So, i need something like:

list1 <- lapply(list1, function(x) {x <- x   annotate("text", label=paste(somevec[x]), x=4, y=4);x})

but this does not work:

Error in somevec[x] : invalid subscript type 'list' 

So, how can i paste the i-th value in somevec into the i-th plot of list1?

CodePudding user response:

We may use Map instead

out <- Map(function(x, y) x   
      annotate('text', label = y, x = 4, y = 4), list1, as.character(somevec))

CodePudding user response:

The problem in your example is that you are trying to use the plot as an index for somevec, x here is a ggplot plot and not an integer like 1 or 2, useful for retrieving elements from somevec. The example below shows how to make a new list with the annotation

require(ggplot2)
#> Loading required package: ggplot2
list1 <- vector("list", 7)
names(list1) <- LETTERS[1:7]
list1 <- lapply(list1, function(x) {x <- ggplot(data.frame())   geom_point()   xlim(0, 10)   ylim(0, 100);x})
somevec <- runif(7)
plist<-mapply(function(x,y){x annotate("text", label=paste(y), x=4, y=4)}, list1, somevec, SIMPLIFY=F)
plist[[1]]

  • Related