Overlapped density plots in ggplot2

后端 未结 3 2033
梦毁少年i
梦毁少年i 2020-12-18 02:25

Imagine I have two vectors each of different length. I want to generate one plot with the density of both vectors overlaid. What I thought I should do is this:



        
相关标签:
3条回答
  • 2020-12-18 02:54

    Everything will work fine if you move the assignment of the colour parameter out of aes().

    vec1 <- data.frame(x=rnorm(2000, 0, 1))
    vec2 <- data.frame(x=rnorm(3000, 1, 1.5))
    
    library(ggplot2)
    
    ggplot() + geom_density(aes(x=x), colour="red", data=vec1) + 
      geom_density(aes(x=x), colour="blue", data=vec2)
    

    enter image description here

    0 讨论(0)
  • 2020-12-18 03:03

    Try this if you want have legends too:

    df <- rbind(data.frame(x=rnorm(2000, 0, 1), vec='1'),
                data.frame(x=rnorm(3000, 1, 1.5), vec='2'))
    ggplot(df, aes(x, group=vec, col=vec)) + geom_density(position='dodge')
    

    0 讨论(0)
  • 2020-12-18 03:04

    I had some troubles with the the above solution, as my data was contained in a single data frame. Using ... data=df$A in the aesthetics doesn't work as this will provide ggplot with a vector of class "numeric", which isn't supported.

    Therefor, to overlay different columns all contained in the same data frame, I'd suggest:

    vec1 <- rnorm(3000, 0, 1)
    vec2 <- rnorm(3000, 1, 1.5)
    
    df <- data.frame(vec1, vec2)
    colnames(df) <- c("A", "B")
    
    library(ggplot2)
    
    ggplot() + geom_density(aes(x=df$A), colour="red") + 
      geom_density(aes(x=df$B), colour="blue")
    

    For most people this might seem obvious, but for me as a beginner, it wasn't. Hope this helps.

    0 讨论(0)
提交回复
热议问题