来自qplot的直方图数据

时间:2012-02-22 07:41:52

标签: r ggplot2

我使用qplot函数生成直方图。它产生了很好的情节,我对图形非常满意。我还想打印直方图数据,有没有办法从qplot()返回对象中检索它?我使用的是hist()函数,如果我们添加选项plot = FALSE,则会提供数据,同样不能使用qplot()

2 个答案:

答案 0 :(得分:1)

您可以使用函数ggplot_build()来获取用于生成ggplot()直方图的实际数据。它们存储在列表元素data中 - 条形的中点位于列x中,计数位于列count中。

 p<-ggplot_build(ggplot(movies,aes(x=rating))+geom_histogram())

 head(p$data[[1]])
    y count    x   ndensity     ncount     density PANEL group ymin ymax xmin xmax
1   0     0 0.75 0.00000000 0.00000000 0.000000000     1     1    0    0  0.6  0.9
2 150   150 1.05 0.02967946 0.02967946 0.008505137     1     1    0  150  0.9  1.2
3 122   122 1.35 0.02413930 0.02413930 0.006917512     1     1    0  122  1.2  1.5
4 199   199 1.65 0.03937475 0.03937475 0.011283482     1     1    0  199  1.5  1.8
5 366   366 1.95 0.07241789 0.07241789 0.020752535     1     1    0  366  1.8  2.1
6 409   409 2.25 0.08092600 0.08092600 0.023190674     1     1    0  409  2.1  2.4

答案 1 :(得分:0)

library(gridExtra)
library(gtable)

fakeDF <- data.frame(group = sample(c('a', 'b', 'c', 'd'), 50, replace = T),
                 rand = sample(50:100, 50))

plot <- ggplot(fakeDF, aes(x = group, y = rand, group = group, fill = group)) +
  geom_bar(stat = 'identity')

table <- tableGrob(head(fakeDF))

grid.arrange(plot,
           table,
           ncol = 2)

enter image description here