簡體   English   中英

累積直方圖與ggplot2

[英]Cumulative histogram with ggplot2

我怎么能得到像這樣的累積直方圖

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

用ggplot2?

我也想畫這樣的多邊形

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

要使累積直方圖使用geom_histogram() ,然后對y值使用cumsum(..count..) 可以使用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")

在此輸入圖像描述

在Didzis的答案的基礎上,這里是一種將ggplot2 (作者:hadley)數據放入geom_line以重現base R hist的外觀的方法。

簡要說明:為了讓bin以與基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

在此輸入圖像描述 在此輸入圖像描述 在此輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM