首页 > 解决方案 > 叠加密度图,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

标签: rggplot2density-plotoverlays

解决方案


您还告诉 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)

这应该会产生所需的图表

图2


推荐阅读