使用ggplot2绘制累积直方图

8
我该如何获得这样的累积直方图?
x <- runif(100,0,10)
h <- hist(x)
h[["counts"]] <- cumsum(h[["counts"]])
plot(h)

使用ggplot2吗?

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

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


把图表作为图像添加如何? - ziggystar
在我的下面的回答中,我尝试了复制。你可以使用theme_bw()theme_classic()更接近。 - PatrickT
2个回答

24

要制作累积直方图,使用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


能否像问题中描述的那样绘制多边形? - Alfredo Sánchez
谢谢您的快速回答,但这并不是我需要的。如果您仔细观察问题中的多边形,每个线段都以该条的右上角结束,而不是中间。 - Alfredo Sánchez
1
如果有人想知道那个神奇的“count”是从哪里来的,请看这里:https://dev59.com/LmUq5IYBdhLWcg3wV_Ii - Mischa

4

在Didzis的回答基础上,以下是一种将ggplot2(作者:hadley)数据转换为geom_line以重现base R hist外观的方法。

简要说明:为了使得柱状图与base 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


1
我知道这个问题已经有4年了,但是我一直在寻找一种方法来解决它,最终我自己解决了。由于我花了一些功夫,所以我想在这里分享一下。 - PatrickT

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接