Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do you relate ggplot2 grobs back to the data?
    primarykey
    data
    text
    <p>Given a ggplot of, for example, points, how would you find out the row of data that a given point corresponded to?</p> <p>A sample plot:</p> <pre><code>library(ggplot2) (p &lt;- ggplot(mtcars, aes(mpg, wt)) + geom_point() + facet_wrap(~ gear) ) </code></pre> <p>We can get the grobs that contain points with <code>grid.ls</code> + <code>grid.get</code>.</p> <pre><code>grob_names &lt;- grid.ls(print = FALSE)$name point_grob_names &lt;- grob_names[grepl("point", grob_names)] point_grobs &lt;- lapply(point_grob_names, grid.get) </code></pre> <p>This last variable contains details of the x-y coordinates, and pointsize, etc. (try <code>unclass(point_grobs[[1]])</code>), but it isn't obvious how I get the row of data in <code>mtcars</code> that each point corresponds to.</p> <hr> <p>To answer kohske's question about why am I doing this, I'm using <code>gridSVG</code> to create an interactive scatterplot. When you roll the mouse over a point, I want to display contextual information. In the mtcars example, I could show a tooltip with the name of the car or other values from that row of the data frame.</p> <p>My hacky idea so far is to include an <code>id</code> column as an invisible text label:</p> <pre><code>mtcars$id &lt;- seq_len(nrow(mtcars)) p + geom_text(aes(label = id), colour = NA) </code></pre> <p>Then traverse the tree of grobs from the point grob to the text grob, and display the row of the dataset indexed by the label.</p> <p>This is fiddly and not very generalisable. If there's a way to store the <code>id</code> value within the point grob, it would be much cleaner.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload