我想绘制回归残差与正态分布的密度。
我找到了一些具有最终结果的代码:
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)
但我的代码如下:
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)
我想绘制“错误”和“normalDist”的密度
我收到错误:
Error in data.frame(x = c(1, 2, 3), fill = structure(function (x, ...) :
arguments imply differing number of rows: 3, 0, 386
谢谢。
答案 0 :(得分:0)
很抱歉,如果我误解了你打算做什么,但为什么你有fill = lines
?
通常,我在那里放一种颜色(或条件,但在你的情况下没有定义线条),例如。
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)
这有帮助吗?
Edit:
我刚才意识到,您是指这个问题:Only one of two densities is shown in ggplot2
如果是这样,请看他将lines
定义为数据框中的序数变量(对行进行分组):
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)