我喜欢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
Run Code Online (Sandbox Code Playgroud)

正如 @krfurlong 在这个问题中向我展示的那样,layer_dataggplot2 中的函数可以准确地为您提供您正在寻找的内容,而无需重新创建数据。
p <- ggplot(iris, aes_string(x = "Sepal.Length")) + stat_ecdf()
p.data <- layer_data(p)
Run Code Online (Sandbox Code Playgroud)
p.data 中的第一列“y”包含 ecdf 值。“x”是绘图中 x 轴上的 Sepal.Length 值。
我们可以重新创建数据:
#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)))
Run Code Online (Sandbox Code Playgroud)
下面的 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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1799 次 |
| 最近记录: |