3

我喜欢 ggplot2 包的stat_ecdf()功能部分,我发现它对于探索数据系列非常有用。然而,这只是视觉上的,我想知道它是否可行 - 如果是的话如何 - 获取关联的表?

请查看以下可重现的示例

p <- ggplot(iris, aes_string(x = "Sepal.Length")) + stat_ecdf() # building of the cumulated chart 
p
attributes(p) # chart attributes
p$data # data is iris dataset, not the serie used for displaying the chart

在此处输入图像描述

4

2 回答 2

2

我们可以重新创建数据:

#Recreate ecdf data
dat_ecdf <- 
  data.frame(x=unique(iris$Sepal.Length),
             y=ecdf(iris$Sepal.Length)(unique(iris$Sepal.Length))*length(iris$Sepal.Length))
#rescale y to 0,1 range
dat_ecdf$y <- 
  scale(dat_ecdf$y,center=min(dat_ecdf$y),scale=diff(range(dat_ecdf$y)))

下面的 2 个图应该看起来相同:

#plot using new data
ggplot(dat_ecdf,aes(x,y)) +
  geom_step() +
  xlim(4,8)

#plot with built-in stat_ecdf
ggplot(iris, aes_string(x = "Sepal.Length")) +
  stat_ecdf() +
  xlim(4,8)
于 2015-05-22T12:59:33.297 回答
2

正如@krfurlong 在这个问题中向我展示的那样,ggplot2 中的layer_data函数可以准确地为您提供所需的内容,而无需重新创建数据。

p <- ggplot(iris, aes_string(x = "Sepal.Length")) + stat_ecdf()
p.data <- layer_data(p)

p.data 中的第一列“y”包含 ecdf 值。“x”是绘图中 x 轴上的 Sepal.Length 值。

于 2020-02-11T18:32:35.573 回答