6

I was wondering whether it is possible to get the transformed data in ggplot2 graphs? In particular, I am interested in getting the coordinates and size of points in dot plots to use them in another plotting library (d3.js). How can I extract that information?

Here is the plot:

g=ggplot(data.frame(x=rnorm(100)), aes(x = x)) + geom_dotplot()

Now I can get the original data using g$data but I want the transformed data (coordinates of the points in the plot).

Thanks!

user2503795
  • 4,035
  • 2
  • 34
  • 49

1 Answers1

9

Use ggplot_build and then extract the data. Try this:

gg <- ggplot_build(g)

The resulting object is a list, with the first element containing the data you're after:

str(gg, max.level=1)
List of 3
 $ data :List of 1
 $ panel:List of 5
  ..- attr(*, "class")= chr "panel"
 $ plot :List of 8
  ..- attr(*, "class")= chr "ggplot"

This is what it looks like:

head(gg$data[[1]])
  y         x  binwidth count ncount     width PANEL group countidx stackpos      xmin      xmax ymin ymax
1 0 -2.070496 0.1356025     1  0.125 0.1356025     1     1        1      0.5 -2.138297 -2.002695    0    1
2 0 -1.781799 0.1356025     2  0.250 0.1356025     1     1        1      0.5 -1.849600 -1.713998    0    1
3 0 -1.781799 0.1356025     2  0.250 0.1356025     1     1        2      1.5 -1.849600 -1.713998    0    1
4 0 -1.619960 0.1356025     1  0.125 0.1356025     1     1        1      0.5 -1.687761 -1.552159    0    1
5 0 -1.403223 0.1356025     6  0.750 0.1356025     1     1        1      0.5 -1.471024 -1.335422    0    1
6 0 -1.403223 0.1356025     6  0.750 0.1356025     1     1        2      1.5 -1.471024 -1.335422    0    1

PS. AFAIK, this feature only became available in ggplot2 version 0.9.0

Andrie
  • 176,377
  • 47
  • 447
  • 496