Get data associated to ggplot + stat_ecdf()

拜拜、爱过 提交于 2020-02-24 18:21:55

问题


I like the stat_ecdf() feature part of ggplot2 package, which I find quite useful to explore a data series. However this is only visual, and I wonder if it is feasible - and if yes how - to get the associated table?

Please have a look to the following reproducible example

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


回答1:


We can recreate the data:

#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)))

Below 2 plots should look the same:

#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)



回答2:


As @krfurlong showed me in this question, the layer_data function in ggplot2 can get you exactly what you're looking for without the need to recreate the data.

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

The first column in p.data, "y", contains the ecdf values. "x" is the Sepal.Length values on the x-axis in your plot.



来源:https://stackoverflow.com/questions/30396755/get-data-associated-to-ggplot-stat-ecdf

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!