从 ggplot 中提取数据 [英] Extract data from a ggplot

查看:42
本文介绍了从 ggplot 中提取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用数据框中的 ggplot2 geom_histogram 绘制了一个图.请参阅下面的示例并链接到 ggplot 直方图 需要使用嵌套的 ddply 函数和 facet wrap 用因子标记每个 geom_vline

I have made a plot using ggplot2 geom_histogram from a data frame. See sample below and link to the ggplot histogram Need to label each geom_vline with the factors using a nested ddply function and facet wrap

我现在需要制作一个数据框,其中包含用于生成上述 ggplot 的汇总数据.

I now need to make a data frame that contains the summarized data used to generate the ggplot above.

Sector2 Family  Year    Length
BUN Acroporidae 2010    332.1300496
BUN Poritidae   2011    141.1467966
BUN Acroporidae 2012    127.479
BUN Acroporidae 2013    142.5940556
MUR Faviidae    2010    304.0405
MUR Faviidae    2011    423.152
MUR Pocilloporidae  2012    576.0295
MUR Poritidae   2013    123.8936667
NTH Faviidae    2010    60.494
NTH Faviidae    2011    27.427
NTH Pocilloporidae  2012    270.475
NTH Poritidae   2013    363.4635

推荐答案

要获得实际绘制的值,您可以使用函数 ggplot_build() 其中参数是您的绘图.

To get values actually plotted you can use function ggplot_build() where argument is your plot.

p <- ggplot(mtcars,aes(mpg))+geom_histogram()+
      facet_wrap(~cyl)+geom_vline(data=data.frame(x=c(20,30)),aes(xintercept=x))

pg <- ggplot_build(p)

这将生成列表,其中一个子列表名为 data.此子列表包含数据框,其中包含绘图中使用的值,例如,对于直方图,它包含 y 值(与 count 相同).如果您使用分面,则 PANEL 列会显示使用了哪些分面值.如果您的图中有多个 geom_ ,则数据将包含每个数据框 - 在我的示例中,直方图有一个数据框,vlines 有另一个数据框.

This will make list and one of sublists is named data. This sublist contains dataframe with values used in plot, for example, for histrogramm it contains y values (the same as count). If you use facets then column PANEL shows in which facet values are used. If there are more than one geom_ in your plot then data will contains dataframes for each - in my example there is one dataframe for histogramm and another for vlines.

head(pg$data[[1]])
  y count         x ndensity ncount density PANEL group ymin ymax
1 0     0  9.791667        0      0       0     1     1    0    0
2 0     0 10.575000        0      0       0     1     1    0    0
3 0     0 11.358333        0      0       0     1     1    0    0
4 0     0 12.141667        0      0       0     1     1    0    0
5 0     0 12.925000        0      0       0     1     1    0    0
6 0     0 13.708333        0      0       0     1     1    0    0
      xmin     xmax
1  9.40000 10.18333
2 10.18333 10.96667
3 10.96667 11.75000
4 11.75000 12.53333
5 12.53333 13.31667
6 13.31667 14.10000

head(pg$data[[2]])
  xintercept PANEL group xend  x
1         20     1     1   20 20
2         30     1     1   30 30
3         20     2     2   20 20
4         30     2     2   30 30
5         20     3     3   20 20
6         30     3     3   30 30

这篇关于从 ggplot 中提取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆