我怎么能得到这样的累积直方图
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()
,然后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")
基于 Didzis 的回答,这是一种将ggplot2
(作者:hadley)数据放入 ageom_line
中以重现base R hist
.
简要说明:为了让 bin 以与基础 R 相同的方式定位,我设置了binwidth=1
和boundary=0
。为了获得相似的外观,我使用了color=black
and fill=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