是否可以获取转换后的绘图数据?(例如点图中点的坐标、密度曲线)

6

我想知道是否可以在ggplot2图表中获取转换后的数据?特别是,我想获取点图中点的坐标和大小,以便在另一个绘图库(d3.js)中使用它们。如何提取这些信息?

以下是该图:

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

现在我可以使用g$data获取原始数据,但我想要转换后的数据(图中点的坐标)。

谢谢!

1个回答

9
使用ggplot_build函数,然后提取数据。尝试以下操作:
gg <- ggplot_build(g)

生成的对象是一个列表,第一个元素包含您需要的数据:
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"

这是它的外观:
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. 据我所知,这个功能只在 ggplot2 0.9.0 版本中可用。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接