I want to plot the density of the residuals of a regression vs. a normal distribution.
I found some code that has the end result:
library(ggplot2)
#Sample data
dat <- data.frame(dens = c(rnorm(100), rnorm(100, 10, 5))
, lines = rep(c("a", "b"), each = 100))
#Plot.
ggplot(dat, aes(x = dens, fill = lines)) + geom_density(alpha = 0.5)
but my code looks like:
residuals<-Regression()$error
normalDist<- rnorm(length(residuals), mean = mean(residuals), sd= sd(residuals))
dat<- data.frame(error = residuals, norm = normalDist)
print(stack(dat))
g<-ggplot(melt(dat), aes(x = error, fill = lines)) + geom_density(alpha = 0.5)
I want to plot the densities of "error" and "normalDist"
I am getting the error:
Error in data.frame(x = c(1, 2, 3), fill = structure(function (x, ...) :
arguments imply differing number of rows: 3, 0, 386
thank you.
Sorry if I misunderstand what you are planning to do, but why do you have fill = lines
? Usually, I put a color there (or a condition, but in your case lines is not defined), eg
require(ggplot2)
residuals<-jitter(rep(0,10))
normalDist<- rnorm(length(residuals), mean = mean(residuals), sd= sd(residuals))
dat<- data.frame(error = residuals, norm = normalDist)
print(stack(dat))
ggplot(dat, aes(x = error, fill = "red")) + geom_density(alpha = 0.5)
Does this help?
Edit:
I just realized, are you referring to this question: Only one of two densities is shown in ggplot2
If so, see that he defined lines
as a ordinal variable in his data frame (to group the rows):
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.