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.
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