How to scale density plots (for several variables) in ggplot having melted data

前端 未结 2 1187
南方客
南方客 2021-02-20 10:53

I have a melted data set which also includes data generated from normal distribution. I want to plot empirical density function of my data against normal distribution but the sc

2条回答
  •  无人共我
    2021-02-20 11:29

    df<-data.frame(type=rep(c('A','B'),each=100),x = rnorm(200,1,2)/10, y = rnorm(200))
    df.m<-melt(df)
    
    require(data.table)
    DT <- data.table(df.m)
    

    Insert a new column with the scaled value into DT. Then plot.

    This is the image code:

    DT <- DT[, scaled := scale(value), by = "variable"]
    str(DT)
    
    ggplot(DT) +
      geom_density(aes(x = scaled, color = variable)) +
      facet_grid(. ~ type)
    
    qplot(data = DT, x = scaled, color = variable,
          facets = ~ type, geom = "density")
    
    # Using fill (inside aes) and alpha outside(so you don't get a legend for it)
    ggplot(DT) +
      geom_density(aes(x = scaled, fill = variable), alpha = 0.2) +
      facet_grid(. ~ type)
    
    qplot(data = DT, x = scaled, fill = variable, geom = "density", alpha = 0.2, facets = ~type)
    
    # Histogram
    ggplot(DT, aes(x = scaled, fill = variable)) +
      geom_histogram(binwidth=.2, alpha=.5, position="identity") +
      facet_grid(. ~ type, scales = "free")
    
    qplot(data = DT, x = scaled, fill = variable, alpha = 0.2, facets = ~type)
    

    enter image description here

提交回复
热议问题