【问题标题】:Cumulative histogram with ggplot2ggplot2的累积直方图
【发布时间】:2013-08-23 18:59:54
【问题描述】:

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

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

使用 ggplot2?

我也想画这样的多边形

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

【问题讨论】:

  • 将情节添加为图像怎么样?
  • 在下面的回答中,我尝试了复制。您可以通过theme_bw()theme_classic() 更进一步。

标签: r ggplot2


【解决方案1】:

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

【讨论】:

  • 是否可以像问题中那样绘制多边形?
  • 感谢您这么快回答,但这并不是我所需要的。如果你仔细观察问题中的多边形,每个线段都在条形的右上角结束,而不是在中间。
  • 如果有人想知道那个魔法 ..count.. 是从哪里来的,请看这里:stackoverflow.com/questions/14570293/…
【解决方案2】:

基于 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

【讨论】:

  • 我知道这个问题已经有 4 年的历史了,但我一直在寻找一种方法来解决这个问题并最终自己解决了这个问题。由于花了我一些力气,我想我会在这里分享它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-12-05
  • 1970-01-01
  • 2013-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多