0

I am trying to overlay a Gaussian on a histogram using R + ggplot2. This is a plot I have done many times before, but now I am getting an error that reads: "Error: length(rows) == 1 is not TRUE."

My 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

Again, this is something I have done many times before. Perhaps it is because I have switched from my work computer to my home computer? I tried updating all of my packages, but this didn't seem to work. I am using RStudio Version 1.1.456, and the output of version is:

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

I have tried to find answers from the previous posts Getting error Error: length(rows) == 1 is not TRUE in R and dplyr Error: length(rows) == 1 is not TRUE in R, with no luck. Any help is greatly appreciated. Thank you in advance.

tlmoore
  • 125
  • 8
  • 1
    Take the `fill = density` out of the first call to `aes`. And don't use `$` in the `aes` - not the problem here, but often is. – Richard Telford Nov 13 '18 at 09:43
  • This works perfect. Thank you so much! Do you mind explaining why it is bad practice to put `$` in the `aes`? Again, thank you. It worked perfectly. – tlmoore Nov 13 '18 at 09:48
  • See https://stackoverflow.com/questions/32543340/issue-when-passing-variable-with-dollar-sign-notation-to-aes-in-combinatio - but apparently this was recently fixed in ggplot. Still, the $ is redundant. – Richard Telford Nov 13 '18 at 09:55
  • Thanks! Always good to learn better practices to avoid breaking things in the future. Much appreciated! – tlmoore Nov 13 '18 at 09:59

1 Answers1

0

The problem is that you are passing the fill before assigning a value to y in aestethics. This works this way

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

enter image description here

Carles
  • 2,731
  • 14
  • 25