r - 叠加密度图,ggplot2,R 3.5.1。,错误:美学必须是长度1或与数据相同
问题描述
我正在尝试使用 Mac 上的 Rstudio R 3.5.1 版创建一个单一的图形,其中包含我的 numeric_var 的 2 个叠加平滑密度图,为我的 factor_var 分层。我总是遇到同样的错误:
"Aesthetics must be either length 1 or the same as the data (): x, fill"
我尝试了多种方法(下面的一个示例)。我也遵循了本指南- STHDA,删除了 NA 并检查了有关此错误的其他问题,但我无法使其正常工作。这就是我想要得到的:
请帮忙?(我是新手,第一个问题,请善待:))
数据
mydata <- fulldata %>%
select(numeric_var,factor_var) %>%
filter(factor_var== 0 | factor_var== 1)
head(mydata)
numeric_var factor_var
1 0.6 0
2 0.7 0
3 0.7 1
4 0.9 0
5 0.6 1
6 0.7 0
情节代码
ggplot(mydata, aes(x = numeric_var, fill = factor_var)) +
geom_density(alpha = 0.5)
错误:
Aesthetics must be either length 1 or the same as the data (598): x, fill
解决方案
您还告诉 ggplot 您希望您的数据由变量分隔,您可以使用以下group
参数轻松做到这一点:
x<-c(0.6,0.7,0.7,0.9,0.6,0.7)
y<-c(0,0,1,0,1,0)
df <- as.data.frame(cbind(x,y))
ggplot(df, aes(x=x,fill=y, group = y))+
geom_density(alpha=0.5)
现在传说不同了,这个结果是因为 ggplot 意识到有一个变量而不是一个字符。实际上它只需要分解,但在您的示例中没有得到它。解决方法如下(我相信有更优雅的解决方案):
x<-c(0.6,0.7,0.7,0.9,0.6,0.7)
y<-as.character(c(0,0,1,0,1,0))
df <- as.data.frame(cbind(x,y))
ggplot(df, aes(x=x, fill=y, group=y))+
geom_density(alpha=0.5)
这应该会产生所需的图表
推荐阅读
- javascript - 模拟输入输入/文本区域
- database - 在 Mac 中安装 Oracle Instant Client 的问题
- azure - 如何从应用程序通过 REST 正确创建团队消息
- c - 内联函数全局范围
- javascript - chrome 扩展本机消息传递 :: 无法连接:与本机消息传递主机通信时出错
- java - Spring Boot - 抛出异常或指示未找到项目
- vue.js - 函数调用中接收到错误的参数
- c# - 添加为连接服务时使用 web.config 配置 WCFservice 客户端(sdk-project 样式)
- github - 如何弃用私有 github 包版本
- docker - 如何让 swagger-ui (docker) 使用特定的请求 URL?