R: Density plot with colors by group?

北慕城南 提交于 2019-12-02 08:47:59

问题


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 one.

I've tried this (example):

library(ggplot2)
AA <- rnorm(100000, 70,20)
BB <- rnorm(100000,120,20)

valores <- c(AA,BB)
grupo <- c(rep("AA", 100000),c(rep("BB", 100000)))
todo <- data.frame(valores, grupo)


ggplot(todo, aes(x=valores, fill=grupo, color=grupo)) +
  geom_histogram(aes(y=..density..), binwidth=3)+  geom_density(aes(color=grupo))

But I'm just getting a graphic with a single line and a single color.

I would like to have different colors for the the two density lines. And if possible the histograms as well.

I've done it with ggplot2 but base R would also be OK.

or I don't know what I've changed and now I get this:

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

but the density lines were not plotted.

or even strange things like


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/38309547/r-density-plot-with-colors-by-group

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!