MYaseen208
MYaseen208

Reputation: 23898

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.

Upvotes: 1

Views: 2125

Answers (2)

Ben Bolker
Ben Bolker

Reputation: 226007

(This might get a better answer on the ggplot mailing list.)

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.

Maybe this does what you want, via some aes_string trickery that substitutes the names of the desired columns ...

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")

Upvotes: 2

Gavin Simpson
Gavin Simpson

Reputation: 174778

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. 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. I presume you mean to plot at x = A and y = B of TData? If so, this works:

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

Upvotes: 2

Related Questions