R: Density plot with colors by group?

后端 未结 2 1111
别跟我提以往
别跟我提以往 2021-01-24 11:56

I have data from 2 populations. I\'d like to get the histogram and density plot of both on the same graphic. With one color for one population and another color for the other on

相关标签:
2条回答
  • 2021-01-24 12:45

    I suggest this ggplot2 solution:

    ggplot(todo, aes(valores, color=grupo)) +
      geom_histogram(position="identity", binwidth=3, aes(y=..density.., fill=grupo),  alpha=0.5) +
      geom_density()
    

    @skan: Your attempt was close but you plotted the frequencies instead of density values in the histogram.

    0 讨论(0)
  • 2021-01-24 12:58

    A base R solution could be:

      hist(AA, probability = T, col = rgb(1,0,0,0.5), border = rgb(1,0,0,1), 
           xlim=range(AA,BB), breaks= 50, ylim=c(0,0.025), main="AA and BB", xlab = "")
      hist(BB, probability = T, col = rgb(0,0,1,0.5), border = rgb(0,0,1,1), add=T)
      lines(density(AA))
      lines(density(BB), lty=2)
    

    For alpha I used rgb. But there are more ways to get it in. See alpha() in the scales package for instance. I added also the breaks parameter for the plot of the AAs to increase the binwidth compared to the BB group.

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