2017-03-07 25 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