2014-11-05 38 views
2

我繪製了一條Z曲線,並使用geom_segment對曲線下方的區域着色。在ggplot中使用stat_function時着色一段曲線

我已經作圖使用

p <- ggplot(data.frame(x = c(-3, 3)), aes(x)) + stat_function(fun = dnorm) 

enter image description here

我想色曲線的段,使得曲線的顏色在x軸的顏色相匹配它下面的Z分佈。

由於我使用的是stat_function,我覺得很少有機會修改它的特徵。

有沒有人嘗試類似的壯舉,並找到了一種方法來做到這一點?

回答

2
dnorm_segment <- function(x, min = 0, max = 1) dnorm(x)*ifelse(x>=min & x<=max, 1, NA) 
zero_segment <- function(x, min = 0, max = 1) ifelse(x>=min & x<=max, 0, NA) 
plot_both <- function(min, max, colour) 
{ 
    args <- list(min = min, max = max) 
    list(
    stat_function(fun = dnorm_segment, col = colour, size = 3, args = args, n = 1001), 
    stat_function(fun = zero_segment, col = colour, size = 3, args = args, n = 1001) 
) 
} 

ggplot(data.frame(x = c(-3, 3)), aes(x)) + 
    stat_function(fun = dnorm) + 
    plot_both(-3, -2, "purple") + 
    plot_both(-2, -1, "yellow") 
# + etc 

enter image description here

+0

美麗的答案,我真的很感動。謝謝! – 2014-11-05 20:21:03

+0

不客氣! – tonytonov 2014-11-06 14:23:57

+0

不幸的是,在使用ggplot2之前,您需要將數據分成子集(手動將其分段)。我們希望看到這個選項直接集成在ggplot2上 – skan 2016-01-29 19:45:51