简体   繁体   English

ggplot2出错

[英]Error with ggplot2

I don't know what am I missing in the code? 我不知道代码中缺少什么?

set.seed(12345)
require(ggplot2)
AData <- data.frame(Glabel=LETTERS[1:7], A=rnorm(7, mean = 0, sd = 1), B=rnorm(7, mean = 0, sd = 1))
TData <- data.frame(Tlabel=LETTERS[11:20], A=rnorm(10, mean = 0, sd = 1), B=rnorm(10, mean = 0, sd = 1))
i <- 2
j <- 3
p <- ggplot(data=AData, aes(AData[, i], AData[, j])) + geom_point() + theme_bw()
p <- p + geom_text(aes(data=AData, label=Glabel), size=3, vjust=1.25, colour="black")
p <- p + geom_segment(data = TData, aes(xend = TData[ ,i], yend=TData[ ,j]),
                  x=0, y=0, colour="black",
                  arrow=arrow(angle=25, length=unit(0.25, "cm")))
p <- p + geom_text(data=TData, aes(label=Tlabel), size=3, vjust=1.35, colour="black")

Last line of the code produces the error. 代码的最后一行产生错误。 Please point me out how to figure out this problem. 请指出如何找出这个问题。 Thanks in advance. 提前致谢。

I have no idea what you are trying to do, but the line that fails is the last line, because you haven't mapped new x and y variables in the mapping. 我不知道你要做什么,但失败的行是最后一行,因为你没有在映射中映射新的x和y变量。 geom_text() needs x and y coords but you only provide the label argument, so ggplot takes x and y from p , which has only 7 rows of data whilst Tlabel is of length 10. That explains the error. geom_text()需要x和y coords但你只提供label参数,所以ggplotp获取x和y,它只有7行数据,而Tlabel的长度为10.这解释了错误。 I presume you mean to plot at x = A and y = B of TData ? 我认为你的意思是绘制在TData =的x = A和y = B? If so, this works: 如果是这样,这有效:

p + geom_text(data=TData, mapping = aes(A, B, label=Tlabel), 
              size=3, vjust=1.35, colour="black")

(This might get a better answer on the ggplot mailing list.) (这可能会在ggplot邮件列表上找到更好的答案。)

It looks like you're trying to display some kind of biplot ... the root of your problem is that you're violating the idiom of ggplot, which wants you to specify variables in a way that's consistent with the scope of the data. 看起来你正在试图显示某种双时隙......问题的根源在于你违反了ggplot的习惯用语,它要求你以与数据范围一致的方式指定变量。

Maybe this does what you want, via some aes_string trickery that substitutes the names of the desired columns ... 也许这会做你想要的,通过一些替代所需列的名称的aes_string ......

varnames <- colnames(AData)[-1]
v1 <- varnames[1]
v2 <- varnames[2]
p <- ggplot(data=AData,
            aes_string(x=v1, y=v2)) + geom_point() + theme_bw()
## took out redundant 'data', made size bigger so I could see the labels
p <- p + geom_text(aes(label=Glabel), size=7, vjust=1.25, colour="black")
p <- p + geom_segment(data = TData, aes_string(xend = v1, yend=v2),
                  x=0, y=0, colour="black",
                  arrow=arrow(angle=25, length=unit(0.25, "cm")))
## added colour so I could distinguish this second set of labels
p <- p + geom_text(data=TData,
                   aes(label=Tlabel), size=10, vjust=1.35, colour="blue")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM