ggplot2: Overlay density plots R

前端 未结 3 1849
名媛妹妹
名媛妹妹 2020-12-13 04:23

I want to overlay a few density plots in R and know that there are a few ways to do that, but they don\'t work for me for a reason or another (\'sm\' library doesn\'t instal

相关标签:
3条回答
  • 2020-12-13 04:35

    Some people have asked if you can do this when the distributions are of different lengths. The answer is yes, just use a list instead of a data frame.

    library(ggplot2)
    library(reshape2)
    x <- list(v1=rnorm(100),v2=rnorm(50,1,1),v3=rnorm(75,0,2))
    data<- melt(x)
    ggplot(data,aes(x=value, fill=L1)) + geom_density(alpha=0.25)
    ggplot(data,aes(x=value, fill=L1)) + geom_histogram(alpha=0.25)
    ggplot(data,aes(x=L1, y=value, fill=L1)) + geom_boxplot()
    
    0 讨论(0)
  • 2020-12-13 04:51

    generally for ggplot and multiple variables you need to convert to long format from wide. I think it can be done without but that is the way the package is meant to work

    Here is the solution, I generated some data (3 normal distributions centered around different points). I also did some histograms and boxplots in case you want those. The alpha parameters controls the degree of transparency of the fill, if you use color instead of fill you get only outlines

    x <- data.frame(v1=rnorm(100),v2=rnorm(100,1,1),v3=rnorm(100,0,2))
    library(ggplot2);library(reshape2)
    data<- melt(x)
    ggplot(data,aes(x=value, fill=variable)) + geom_density(alpha=0.25)
    ggplot(data,aes(x=value, fill=variable)) + geom_histogram(alpha=0.25)
    ggplot(data,aes(x=variable, y=value, fill=variable)) + geom_boxplot()
    

    enter image description here

    0 讨论(0)
  • 2020-12-13 05:01

    For the sake of completeness, the most basic way to overlay plots based on a factor is:

    ggplot(data, aes(x=value)) + geom_density(aes(group=factor))
    

    But as @user1617979 mentioned, aes(color=factor) and aes(fill=factor) are probably more useful in practice.

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