Data driven plot names in data.table

Here is the data.table solution, though again, not what I would recommend:

make_plot <- function(dat, grp.name) {
  print(
    ggplot(dat, aes(x=x, y=y)) + 
    geom_point() + labs(title=paste0("Group: ", grp.name$grp))
  )
  NULL
}    
DT[, make_plot(.SD, .BY), by=grp]

What you really should do for this particular application is what @dmartin recommends. At least, that's what I would do.


Instead of using data.table, you could use facet_grid in ggplot with the labeller argument:

p <- ggplot(data=DT, aes(x = x, y = y)) + aes(shape = factor(grp)) +
     geom_point(aes(colour = factor(grp), shape = factor(grp)), size = 3) + 
     facet_grid(. ~ grp, labeller = label_both)

See the ggplot documentation for more information.


I see you already have a "facetting" option. I had done this

 p+facet_wrap('grp')

But this gives the same result:

 p+facet_wrap(~grp)

enter image description here