4

我打算创建一个箱线图并突出成对比较的显着性水平。这已经在之前的帖子中处理过了。

当我对我的数据集执行相同操作时,我收到以下错误:

 "Incompatible lengths for set aesthetics: x, y"

这是一个示例数据集来说明问题 -

data1<-data.frame(island = c("A", "B", "B", "A", "A"), count = c(2, 5, 12, 2, 3))
g1<-ggplot(data1) +  geom_boxplot(aes(x = factor(island), y = count)) 
g1 + geom_path(x = c(1, 1, 2, 2), y = c(25, 26, 26, 25))  

运行代码的第三行时出现错误,而箱线图结果正常。我怀疑我错过了一些非常微不足道的事情,但我无法抓住它。我将不胜感激任何帮助。

4

2 回答 2

4

因为您没有明确的data参数 in geom_path,所以data参数 in的数据ggplot被“继承”到geom_path。当机器发现 'data1' 中的 x 和 y 变量的长度与geom_path调用中的 x 和 y 向量的长度不同时,它就会窒息。尝试为geom_path并使用data参数创建一个单独的数据框:

data2 <- data.frame(x = c(1, 1, 2, 2), y = c(25, 26, 26, 25))

ggplot(data = data1, aes(x = factor(island), y = count)) +
  geom_boxplot() +
  geom_path(data = data2, aes(x = x, y = y))

在此处输入图像描述

于 2013-10-29T12:50:39.883 回答
0

我将此添加为答案,因为它太长而无法成为评论,但它是作为已接受答案的补充。

在类似的情况下,我尝试使用geom_path彩色条形图,但出现此错误:

Error in eval(expr, envir, enclos) : object 'Species' not found

然后事实证明该fill选项应该“关闭”,否则它会跟随前面ggplot调用中的那个,它要求Species列并导致这样的错误。

## ## Load the libraries
require(data.table)
require(ggplot2)

## ## Make toy data
data1 <- data.table(iris)[,list(value=Petal.Length,Species)]

## ## Draw the bars
p <- ggplot(data=data1,aes(x=Species,y=value,fill=Species)) +
  geom_boxplot() +
  scale_x_discrete(breaks=NULL)

## ## Add lines and an annotation
y1 <- data1[Species=="setosa",max(value)]*1.02
y2 <- y3 <- data1[,max(value)]*1.05
y4 <- data1[Species=="virginica",max(value)]*1.005
data2 <- data.frame(x.=c(1,1,3,3),y.=c(y1,y2,y3,y4))

p <- p +
  ## geom_path(data=data2,aes(x=x.,y=y.)) + # the line that cause the ERROR
  geom_path(data=data2,aes(x=x.,y=y.,fill=NULL)) + # the corrected line
  annotate("text",x=2,y=y3,label="***")
p

在此处输入图像描述

于 2016-05-12T12:49:41.983 回答