Fre*_*son 1 r ggplot2 aesthetics
我不得不承认我已经有一段时间没有使用 ggplot 了,但这似乎有点傻。我在尝试制作密度图时遗漏了一些基本的东西,或者 ggplot2 (v3.3.2) 中存在错误
test <- data.frame(Time=rnorm(100),Age=rnorm(100))
ggplot(test,aes(y=Time,x=Age)) +
geom_density(aes(y=Time,x=Age))
Run Code Online (Sandbox Code Playgroud)
产生
ggplot(测试,aes(y=时间,x=年龄))+
- geom_density(aes(y=Time,x=Age)) 错误:geom_density 需要以下缺失的美学:y
怎么会缺少“y”美学?
小智 6
使用时有两种情况geom_density()。这取决于您指定的统计层:
如果您将情况 1) 和 2) 混合,就会出现您的问题。但我同意,错误消息不是很清楚,可以提及以确保使用的统计数据是所需的统计数据。
library(ggplot2)
test <- data.frame(time = rnorm(100), age = rnorm(100))
#if you want to use precalculated y values you have to change the used stat to identity:
ggplot(test) +
geom_density(aes(x = age, y = time),
stat = "identity")
Run Code Online (Sandbox Code Playgroud)

# compared to the case with the default value of stat: stat = "density"
ggplot(test) +
geom_density(aes(x = age))
Run Code Online (Sandbox Code Playgroud)

由reprex 包(v0.3.0)于 2020 年 8 月 4 日创建