nicfit
nicfit

Reputation: 43

Create multiple lattice plots from a data table using lapply

I am trying to generate mean values by group for each of numerous variables (species) and then plot each of these separately. I have tried list and data table formats. The base plot function works in a for loop:

library(data.table)

      for (i in 3:5) {
      # generate a list of mean value for the species in column number i
      temp <- v2[, lapply(.SD, mean), by="Season", .SDcols=i]
      # plot each col of the list as a scatterplot with main title = header of 2nd col
      plot(temp[[2]]~temp[[1]], main = colnames(temp)[[2]])
    }

But when I try to create lattice plots only a single plot is generated for the last variable:

library(data.table)
library(lattice)

for (i in 3:5) {
  # generate a list of mean value by season for the species in column number i
  temp <- v2[, lapply(.SD, mean), by=c("Season", "Location"), .SDcols=i]
  # Each group in a separate mini plot
  xyplot(temp[[3]]~temp[[1]] | temp[[2]], main = colnames(temp)[3])
}

Have tried saving or printing each lattice plot, is that the right idea? Perhaps I am going about this the wrong way altogether?

Here is a small sample of my data:

    structure(list(Location = structure(c(1L, 1L, 1L, 1L, 4L, 4L, 
4L, 6L, 6L, 1L), .Label = c("BN", "BS", "GN", "GS", "SB", "SL"
), class = "factor"), Season = c(1981L, 1981L, 1981L, 1981L, 
1995L, 1995L, 1995L, 1997L, 1997L, 2000L), Agrostis.magellanica = c(0.3, 
0.3, 0.3, 0.01, 0.6, 0.3, 0.3, 0.3, 0.6, 0.05), Festuca.contracta = c(0.6, 
0.05, 0.3, 0.01, 0.01, 0, 0, 0, 0.01, 0.05), Poa.annua = c(0.01, 
0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.05, 0.01, 0.01)), .Names = c("Location", 
"Season", "Agrostis.magellanica", "Festuca.contracta", "Poa.annua"
), class = c("data.table", "data.frame"), row.names = c(NA, -10L
)

Upvotes: 0

Views: 614

Answers (1)

IRTFM
IRTFM

Reputation: 263411

This is in the R-FAQ. Need a print statement around grid graphics (lattice or ggplot) when used inside a function, and the for loop is a function:

# Needed
require(data.table)  # before defining the object.

pdf()  # pdf is a multipage device.
for (i in 3:5) {
  # generate a list of mean value by season for the species in column number i
  temp <- v2[, lapply(.SD, mean), by=c("Season", "Location"), .SDcols=i]
  # Each group in a separate mini plot
  print( xyplot(temp[[3]]~temp[[1]] | temp[[2]], main = colnames(temp)[3]) )
}
dev.off()  # Failing to properly close a file graphics device is common error.

Upvotes: 2

Related Questions