Only one of two densities is shown in ggplot2

血红的双手。 提交于 2019-12-13 03:04:33

问题


So I have two sets of data (of different length) that I am trying to group up and display the density plots for:

dat <- data.frame(dens = c(nEXP,nCNT),lines = rep(c("Exp","Cont")))
ggplot(dat, aes(x = dens, group=lines, fill = lines)) + geom_density(alpha = .5)

when I run the code it spits an error about the different lengths, i.e. "arguments imply different num of rows: x, y"

I then augment the code to:

dat <- data.frame(dens = c(nEXP,nCNT),lines = rep(c("Exp","Cont"),X))

Where X is the length of the longer argument so the lengths of "lines" will match that of dens.

Now the issue is that when when I go to plot the data I am only getting ONE density plot.... I know there should be two, since plotting the densities with plot/lines, is clearly two non-equal overlapping distributions, so I am assuming the error is with the grouping...

hope that makes sense.


回答1:


So I am not sure why but basically I simply had to do the rep() function manually:

A<-data.frame(ExpN, key = "exp")
B<-data.frame(ConN,key = "con")
colnames(A) <- c("a","key")
colnames(B) <- c("a","key")
dat <- rbind(A,B)
ggplot(dat, aes(x = dens, fill = key)) + geom_density(alpha = .5) 



回答2:


You need to tell rep how many times to repeat each element to get it to line up

dat <- data.frame(dens = c(nEXP,nCNT),
                  lines = rep(c("Exp","Cont"), c(length(nEXP),length(nCNT)))

That should give you a dat you can use with your ggplot call.



来源:https://stackoverflow.com/questions/17604771/only-one-of-two-densities-is-shown-in-ggplot2

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