Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to get the transformed plot data? (e.g. coordinates of points in dot plot, density curve)

Tags:

r

ggplot2

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!

like image 278
user2503795 Avatar asked Aug 31 '12 15:08

user2503795


People also ask

Which argument of Ggplot can be used to add customization to plots?

To customize the plot, the following arguments can be used: alpha, color, linetype, shape, size and fill. Learn more here: ggplot2 box plot.

Which function can you use to create a different plot for each type of cut of diamond?

ggplot(data = diamonds) + geom_bar(mapping = aes(x = color, fill = cut)) +

Which layer in ggplot2 controls the appearance of plot?

The aesthetic layer maps variables in our data onto scales in our graphical visualization, such as the x and y coordinates. In ggplot2 the aesthetic layer is specified using the aes() function. Let's create a plot of the relationship between Sepal.


1 Answers

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

like image 95
Andrie Avatar answered Sep 17 '22 00:09

Andrie