使用 ggplot2 在直方图上绘制高斯分布并得到 "Error length(rows) == 1 is not TRUE"

Plotting Gaussian over histogram with ggplot2 and getting "Error length(rows) == 1 is not TRUE"

我正在尝试使用 R + ggplot2 在直方图上叠加高斯分布。这是我以前做过很多次的情节,但现在我收到一条错误消息:"Error: length(rows) == 1 is not TRUE."

我的 MWE:

library(ggplot2)
df <- data.frame("x" = rnorm(1000, 100,10)) # Sample data

p <- ggplot(df, aes(df$x, fill = ..density..))+
    geom_histogram(aes(y = ..density..), bins = 20)+
    stat_function(fun = dnorm, args = list(mean = mean(df$x), sd = sd(df$x)))+
    theme_bw()+
    theme(aspect.ratio = 1,
        panel.grid = element_blank(),
        legend.position = 'none')
p

同样,这是我以前做过很多次的事情。也许是因为我已经从工作电脑切换到家用电脑了?我尝试更新我所有的包,但这似乎没有用。我使用的是 RStudio 版本 1.1.456,version 的输出是:

platform       x86_64-pc-linux-gnu         
arch           x86_64                      
os             linux-gnu                   
system         x86_64, linux-gnu           
status                                     
major          3                           
minor          4.4                         
year           2018                        
month          03                          
day            15                          
svn rev        74408                       
language       R                           
version.string R version 3.4.4 (2018-03-15)
nickname       Someone to Lean On

我试图从以前的帖子中找到答案 Getting error Error: length(rows) == 1 is not TRUE in R and dplyr Error: length(rows) == 1 is not TRUE in R,但没有成功。任何帮助是极大的赞赏。提前谢谢你。

问题是您在给美学中的 y 赋值之前传递了 fill。 这样工作

p <- ggplot(df, aes(x = x))+
  geom_histogram(aes(y = ..density.., fill = ..density..), bins = 20)+
  stat_function(fun = dnorm, args = list(mean = mean(df$x), sd = sd(df$x)))+
  theme_bw()+
  theme(aspect.ratio = 1,
        panel.grid = element_blank(),
        legend.position = 'none')
p