2017-02-28 46 views
0

如何在兩端添加陰影,如下圖所示?如何在密度分佈圖的兩端添加兩個陰影

我想從0一端添加到-.995和1.995至INF

plot

我想這裏的解決方案https://stackoverflow.com/a/4371473/3133957,但它似乎並沒有工作。

這裏我的代碼

tmpdata <- data.frame(vals = t.stats) 
qplot(x = vals, data=tmpdata, geom="density", 
     adjust = 1.5, 
    xlab="sampling distribution of t-statistic", 
    ylab="frequency") + 
    geom_vline(xintercept = t.statistic(precip, population.precipitation), 
       linetype = "dashed") + 
    geom_ribbon(data=subset(tmpdata,vals>-1.995 & vals<1.995),aes(ymax=max(vals),ymin=0,fill="red",alpha=0.5)) 

回答

0

您沒有爲你的問題提供了一個數據集,所以我模擬一個用於這個答案。首先,讓你的密度圖:

tmpdata <- data.frame(vals = rnorm(10000, mean = 0, sd = 1)) 
plot <- qplot(x = vals, data=tmpdata, geom="density", 
      adjust = 1.5, 
      xlab="sampling distribution of t-statistic", 
      ylab="frequency") 

然後,提取由ggplot使用的x和y座標繪製的密度曲線:

area.data <- ggplot_build(plot)$data[[1]] 

然後,您可以添加兩個geom_area層遮陽左並通過你的曲線向右尾巴:

plot + 
geom_area(data=area.data[which(area.data$x < -1.995),], aes(x=x, y=y), fill="skyblue") + 
geom_area(data=area.data[which(area.data$x > 1.995),], aes(x=x, y=y), fill="skyblue") 

這會給你下面的情節:

enter image description here

注意,您可以在此之後添加geom_vline層(我離開它,因爲它需要的數據,你沒有在你的問題提供)。

+0

謝謝!我不知道我應該使用'ggplot_build'來獲取x,y座標 – prideloki