Overlapped density plots in ggplot2

后端 未结 3 2035
梦毁少年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

提交回复
热议问题