2017-03-07 98 views
1

我正在试图找到在R中的barplot和曲线/正常图之间形成的区域。我使用ggplot2软件包进行所有绘图,并使用gglocator来标识坐标。但是我很难弄清楚如何计算曲线之间的面积。 barplot将保持不变,但曲线会改变(因为它是df的每一行)。计算R中两个图之间的面积

这里是类似我的问题的可重复码:

require(ggplot2) 
require(ggmap) 

x1 <- seq(1, 1000, 25) 
x2 <- rnorm(40, mean = 1, sd = 0.25) 
df <- data.frame(x1, x2) 
bardf <- data.frame(x = c(150,500,750), 
        height = c(1.4, 1.4, 1.2), 
        width = c(50,70,90)) 
p <- ggplot() + 
    geom_bar(data = bardf, aes(x,height, width = width), fill = "white", stat = "identity") + 
    geom_line(data = df, aes(x1,x2)) 

print(p) 
gglocator() 

这是剧情: to find: area between barplot and under the curve

地发现:barplot之间,曲线下面积(请忽略红圈)。 任何人都有任何想法如何继续这个挑战。我在SO中发现了几个关于计算面积的问题,但其中大部分都是针对ROC或者仅仅是为该区域着色。任何建议/想法将不胜感激。

+1

不要试图ggplot本身做到这一点;虽然它可能是可能的,但它是一个用于绘图而不是计算的软件包。相反,只需使用“集成”,例如'整合(approxfun(df $ x1,df $ x2),125,175)' – alistaire

+0

...并且如果该栏可以低于该行,则将'approxfun'包装在另一个函数中,该函数使用适当的值调用'pmin' 。 – alistaire

+0

@alistaire感谢您的回复。我想到了使用集成功能。但是我的问题,就像这个情节一样,可能会有多个峰值或者低点在这些barplot边界之间。所以我想知道是否有一个函数提供多个点而不是插值的上限和下限,然后我可以使用它的集成。那么你知道任何其他函数approxfun()允许这个吗? – snair1591

回答

2

如果您使用approxfun构建将插入点的函数,则可以使用integrate来计算面积。如果栏可以比线下,pmin可以返回高度的降低:

library(ggplot2) 
set.seed(1) # returns a line partially higher than a bar 

df <- data.frame(x1 = seq(1, 1000, 25), 
       x2 = rnorm(40, mean = 1, sd = 0.25)) 
bardf <- data.frame(x = c(150,500,750), 
        height = c(1.4, 1.4,1.2), 
        width = c(50,70,90)) 

ggplot() + 
    geom_col(data = bardf, aes(x, height, width = width), fill = "white") + 
    geom_line(data = df, aes(x1, x2)) 

# iterate in parallel over bardf to calculate all areas at once 
mapply(function(x, h, w){ 
    integrate(function(v){pmin(approxfun(df$x1, df$x2)(v), h)}, 
       lower = x - .5 * w, 
       upper = x + .5 * w 
    )$value}, 
    bardf$x, bardf$height, bardf$width) 
#> [1] 52.40707 83.28773 98.38771 
+1

谢谢!看起来会做这份工作! – snair1591

+0

还有一个问题,无论如何,我可以在这个阴谋阴影计算的区域? – snair1591

+0

你可以用'geom_area'来完成,但是你可能需要重新排列你的数据以使其工作。 – alistaire