累积直方图与ggplot2

时间:2013-08-21 12:01:17

标签: r ggplot2

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

x <- runif(100,0,10)
h <- hist(x)
h[["counts"]] <- cumsum(h[["counts"]])
plot(h)

使用ggplot2?

我还想画一个这样的多边形

lines(h[["breaks"]],c(0,h[["counts"]]))

2 个答案:

答案 0 :(得分:15)

要使累积直方图使用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")

enter image description here

答案 1 :(得分:2)

根据Didzis的回答,这里有一种方法可以将ggplot2(作者:hadley)数据转换为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")

可能有更简单的方法提醒你!碰巧的是,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

enter image description here enter image description here enter image description here