R 叠加密度,非排他性子集

R 叠加密度,非排他性子集,r,ggplot2,R,Ggplot2,我需要在一个图上有几个密度函数。每个密度对应于我的整个数据集的一个子集。子集由数据集中某个变量的值定义 具体来说,我想画一个1年、3年和10年的密度函数。当然,10年的期限包括较短的期限。同样,应根据去年的数据构建3年期水平密度。 子集需要对应于数据[period==1,],数据[period处理依赖分组的方法之一是基于现有分组创建独立分组。下面我选择的方法是创建三个新列(period\u One,period\u three和period\u ten)使用mutate功能,其中 period

我需要在一个图上有几个密度函数。每个密度对应于我的整个数据集的一个子集。子集由数据集中某个变量的值定义

具体来说,我想画一个1年、3年和10年的密度函数。当然,10年的期限包括较短的期限。同样,应根据去年的数据构建3年期水平密度。
子集需要对应于
数据[period==1,]
数据[period处理依赖分组的方法之一是基于现有分组创建独立分组。下面我选择的方法是创建三个新列(
period\u One
period\u three
period\u ten
)使用
mutate
功能,其中

  • period\u one
    =期间的最佳当前EV到EBITDA值==1

  • period\u three
    =period的最佳当前EV TO\u EBITDA值不是
    数据[period==1,]
    数据的一部分[period@AdamQuek是的,没错。子集不是相互排斥的,这是造成麻烦的原因。太好了,非常感谢。如果您有更多的时间,请毫不犹豫地添加一些解释。Thx。编辑了上面答案中的解释。如果您需要更多解释,请告诉我。
      ggplot() +
        geom_density(data = data[period <=3,], aes(x=BEST_CUR_EV_TO_EBITDA), alpha=.2, fill="red") +
        geom_density(data = data[period ==1,], aes(x=BEST_CUR_EV_TO_EBITDA), alpha=.2, fill="grey") +
        geom_density(data = data, aes(x=BEST_CUR_EV_TO_EBITDA), alpha=.2, fill="green")
    
    ggplot(data, aes(x=BEST_CUR_EV_TO_EBITDA, color=period)) +
      geom_density(alpha=.2, fill="blue")
    
    library(data.table)
    library(lubridate)
    library(ggplot2)
      YEARS <- 10
      today <- Sys.Date()
      lastYr <- Sys.Date()-years(1)
      last3Yr <- Sys.Date()-years(3) 
      start.date  = Sys.Date()-years(YEARS)
      date = seq(start.date, Sys.Date(), by=1)
      BEST_CUR_EV_TO_EBITDA <- rnorm(length(date), 3,1)
      data <- cbind.data.frame(date, BEST_CUR_EV_TO_EBITDA)
      data <- cbind.data.frame(data, period = rep(10, nrow(data)))
    
      subPeriods <- function(aDf, from, to, value){
        aDf[aDf$date >= from & aDf$date <= to, "period"] = value
        return(aDf)
      }
    
      data <- subPeriods(data, last3Yr, today, 3)
      data <- subPeriods(data, lastYr, today, 1)
      data <- data.table(data)
    
    
    
      colScale <- scale_colour_manual(
        name = "horizon"
        , values = c("1 Y" = "grey", "3 Y" = "red", "10 Y" = "green"))
    
      ggplot() +
        geom_density(data = data[period <=3,], aes(x=BEST_CUR_EV_TO_EBITDA), alpha=.2, fill="red") +
        geom_density(data = data[period ==1,], aes(x=BEST_CUR_EV_TO_EBITDA), alpha=.2, fill="grey") +
        geom_density(data = data, aes(x=BEST_CUR_EV_TO_EBITDA), alpha=.2, fill="green") +
        colScale
    
    df2 <- data %>% 
        mutate(period_one=ifelse(period==1, BEST_CUR_EV_TO_EBITDA, NA),
                period_three=ifelse(period<=3, BEST_CUR_EV_TO_EBITDA, NA),
                period_ten=BEST_CUR_EV_TO_EBITDA) %>%
       select(date, starts_with("period_")) %>%
       gather(period, val, period_one, period_three, period_ten)
    
    ggplot(df2, aes(val, fill=period)) + geom_density(alpha=.2)