-1

I am trying to understand the following segment, especially the one, sapply(tmp$grobs, function(x) x$name

require(gridExtra)
require(ggplot2)
my_hist <- ggplot(diamonds, aes(clarity, fill=cut)) + geom_bar()
tmp <- ggplot_gtable(ggplot_build(my_hist))
leg <- which(sapply(tmp$grobs, function(x) x$name) ==  "guide-box")
legend <- tmp$grobs[[leg]]

I think this function is used to extract the name of tmp$grobs, which is shown as follows

enter image description here

Then I tried. First question, how to understand the structure, like [[1]]; further, why (tmp$grobs[1])$name just does not work.

enter image description here

user288609
  • 12,465
  • 26
  • 85
  • 127
  • 1
    Use `[[`: `tmp$grobs[[1]]$name` should work. – agstudy Sep 21 '14 at 20:56
  • `[1]` doesn't work simply because `tmp` is a list, try `typeof(tmp)`. Please read [this r-faq](http://stackoverflow.com/questions/1169456/in-r-what-is-the-difference-between-the-and-notations-for-accessing-the). Then, read [this r-faq](http://stackoverflow.com/questions/3505701/r-grouping-functions-sapply-vs-lapply-vs-apply-vs-tapply-vs-by-vs-aggrega) – David Arenburg Sep 21 '14 at 21:02

1 Answers1

2

this isn't an answer to your question, but a coding suggestion

require(ggplot2)
my_hist <- ggplot(diamonds, aes(clarity, fill=cut)) + geom_bar()
tmp <- ggplotGrob(my_hist)
legend <- tmp$grobs[[grep("guide-box", tmp$layout$name)]]
baptiste
  • 75,767
  • 19
  • 198
  • 294