累积直方图与ggplot2

Alf*_*hez 3 r ggplot2

我怎么能得到像这样的累积直方图

x <- runif(100,0,10)
h <- hist(x)
h[["counts"]] <- cumsum(h[["counts"]])
plot(h)
Run Code Online (Sandbox Code Playgroud)

用ggplot2?

我也想画这样的多边形

lines(h[["breaks"]],c(0,h[["counts"]]))
Run Code Online (Sandbox Code Playgroud)

Did*_*rts 16

使累积直方图使用geom_histogram()然后cumsum(..count..)用于y值.累计行可以添加stat_bin()geom="line"y值计算为cumsum(..count..).

ggplot(NULL,aes(x))+geom_histogram(aes(y=cumsum(..count..)))+
       stat_bin(aes(y=cumsum(..count..)),geom="line",color="green")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


Pat*_*ckT 4

基于 Didzis 的答案,这里有一种将ggplot2(作者:hadley)数据放入 a 中geom_line以重现base R hist.

简要说明:为了让垃圾箱以与底座 R 相同的方式定位,我设置了binwidth=1boundary=0。为了获得类似的外观,我使用了color=blackfill=white。为了获得线段的相同位置,我使用了ggplot_build. 您会发现 Didzis 使用此技巧的其他答案。

# make a dataframe for ggplot
set.seed(1)
x = runif(100, 0, 10)
y = cumsum(x)
df <- data.frame(x = sort(x), y = y)

# make geom_histogram 
p <- ggplot(data = df, aes(x = x)) + 
    geom_histogram(aes(y = cumsum(..count..)), binwidth = 1, boundary = 0,
                color = "black", fill = "white")

# extract ggplot data
d <- ggplot_build(p)$data[[1]]

# make a data.frame for geom_line and geom_point
# add (0,0) to mimick base-R plots
df2 <- data.frame(x = c(0, d$xmax), y = c(0, d$y))

# combine plots: note that geom_line and geom_point use the new data in df2
p + geom_line(data = df2, aes(x = x, y = y),
        color = "darkblue", size = 1) +
    geom_point(data = df2, aes(x = x, y = y),
        color = "darkred", size = 1) +
    ylab("Frequency") + 
    scale_x_continuous(breaks = seq(0, 10, 2))

# save for posterity
ggsave("ggplot-histogram-cumulative-2.png")
Run Code Online (Sandbox Code Playgroud)

请注意,可能还有更简单的方法!碰巧 ggplot 对象还存储另外两个值x:最小值和最大值。所以你可以用这个方便的函数制作其他多边形:

# Make polygons: takes a plot object, returns a data.frame
get_hist <- function(p, pos = 2) {
    d <- ggplot_build(p)$data[[1]]
    if (pos == 1) { x = d$xmin; y = d$y; }
    if (pos == 2) { x = d$x; y = d$y; }
    if (pos == 3) { x = c(0, d$xmax); y = c(0, d$y); }
    data.frame(x = x, y = y)
}
df2 = get_hist(p, pos = 3)  # play around with pos=1, pos=2, pos=3
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述 在此输入图像描述 在此输入图像描述