r - Plotting Gaussian over histogram with ggplot2 and getting "Error length(rows) == 1 is not TRUE"
问题描述
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
推荐阅读
- python - 在 Jupyter 笔记本中重新加载 Python 模块(不自动重新加载)
- android - 快速启动状态选择后模拟器关闭
- javascript - 在单文件组件方法中使用 vue-styled-components
- ios - 与文本字段的用户默认值比较
- angular - 然后如何以角度2返回Promise的数据
- php - 教义 - 实体侦听器中注入实体之间的区别
- python - 加快python图像颜色阈值/过滤
- javascript - Babel 7 Jest Core JS “TypeError:wks 不是函数”
- bash - 比较文件文件,提示不要求输入
- confluence - 获取匿名空间权限,即使匿名已停用