geom_ribbon用于可变级别

时间:2018-09-26 09:08:49

标签: r ggplot2

我正在绘制一些分析结果,在这种情况下,我尝试用黑色填充下面的区域,该区域是可变阈值的黑线。我对<div> <input type="text" id="in1" onkeyup="enablesecond()";/> <input type="text" id="in2" disabled="true"/> </div> <script> var text1 = document.getElementById("in1"); text1.onkeyup = function () { if (this.value != "" || this.value.length > 0) { document.getElementById("in2").disabled = false; } else { document.getElementById("in2").disabled = true; } } </script>做过类似的事情,但考虑到固定的阈值。

这是我正在使用的数据:

geom_ribbon

这是原始图(黑色为可变阈值)

Original plot

这就是我试图通过 df <- data.frame(month= seq(560,624,1), US= c(0.67,0.71,1.49,3.47,8.13,12.13,10.52,9.33,5.48,2.72,1.74, 0.16,0.04,0.15,0.76,0.94,10.60,26.50,15.09,17.93, 15.68,11.69,7.00,3.68,0.46,0.55,1.21,4.14,12.73, 10.24,10.89,22.13,18.76, 18.99,9.76,2.24,0.92,0.29, 0.38,4.92,4.17,2.29,1.92,1.69, 14.87,12.32,2.00,0.67, 0.12,0.06,0.80,4.41,6.70,18.61,7.21,43.62,23.64,12.83, 6.00,2.16,0.69,0.16,3.18,8.87,16.45), lim= c(0.63,0.41,1.20,3.11,4.21,5.75,4.88,6.21,8.33,4.34,2.07, 1.16,0.63,0.41,1.20,3.11,4.21,5.75,4.88,6.21,8.33,4.34, 2.07,1.16,0.63,0.41,1.20,3.11,4.21,5.75,4.88,6.21,8.33, 4.34,2.07,1.16,0.63,0.41,1.20,3.11,4.21,5.75,4.88,6.21, 8.33,4.34,2.07,1.16,0.63,0.41,1.20,3.11,4.21,5.75,4.88, 6.21,8.33,4.34,2.07,1.16,0.63,0.41,1.20,3.11,4.21)) ggplot(df,aes(x=month,y=US)) + geom_line(col='deepskyblue4')+ geom_line(aes(y=df[,'lim']))+ theme_bw() 获得的结果,但是我不知道该怎么做:

enter image description here

建议将不胜感激。

谢谢。

2 个答案:

答案 0 :(得分:1)

您可以使用geom_ribbon,但首先需要稍微处理一下数据。

library(tidyverse)
#set US to lim if lim > US
df2 <- df %>% 
  mutate(US = if_else(lim > US, US, lim))


ggplot(df,aes(x=month,y=US)) +
  geom_ribbon(data = df2, aes(x = month, ymin = US, ymax = lim), fill = "pink") +
  geom_line(col='deepskyblue4')+
  geom_line(aes(y=lim))+      
  labs(title=paste('Station',sep=' '),x="Nº months", y = "Hm3",size=2)+
  theme_bw()

答案 1 :(得分:1)

如果您将geom_ribbonymin中的一个设置为ymax值,则可以使用NA填充:

x

编辑: 如果要填补空白,可以对数据进行插值以获得更好的图:

ggplot(df, aes(x = month, 
               ymin = ifelse(lim>US, lim, NA), 
               ymax = US, 
               y = US)) +
  geom_ribbon(fill = "pink") +
  geom_line(color = "deepskyblue4")+
  geom_line(aes(y = lim))+
  theme_bw()