I\'ve tough time with ggplot2 when used in function or S4. Here is my code without function:
rm(list=ls(all=TRUE))
library(nlme)
data(Oats)
Data <- Oats
Just add a label
columns to the data frames.
Also, note that you should never have a $ inside aes
.
This should work:
G1 <- data.frame(G, label=rownames(G))
E1 <- data.frame(E, label=rownames(E))
library(ggplot2)
r <- 0.08
p <- ggplot(data=G1, aes(PC1, PC2)) + geom_point() + theme_bw()
p <- p + geom_text(aes(label=label), size=3, vjust=1.25, colour="black")
p <- p + geom_path(data=as.data.frame(con.hull), aes(PC1, PC2))
p <- p + geom_segment(data=as.data.frame(E), aes(xend = PC1, yend=PC2),
x=0, y=0, colour="black",
arrow=arrow(angle=25, length=unit(0.25, "cm")))
p <- p + geom_text(data=E1, aes(label=label),
size=3, vjust=1.35, colour="black")
p <- p + labs(list(x=sprintf("PC1 (%.1f%%)", PC.Percent.SS[1]),
y=sprintf("PC2 (%.1f%%)", PC.Percent.SS[2])))
p <- p + opts(axis.title.x=theme_text(size=10, hjust=0.54, vjust=0))
p <- p + opts(axis.title.y=theme_text(size=10, angle=90, vjust=0.25))
p <- p + xlim(range(c(E[ ,1], G[ ,1])) + range(c(E[ ,1], G[ ,1]))*r)
p <- p + ylim(range(c(E[ ,2], G[ ,2])) + range(c(E[ ,2], G[ ,2]))*r)
p <- p + geom_segment(data=tmp, aes(xend=V1, yend=V2), x=0, y=0)
print(p)
You have to set as.data.frame(G) outside of your ggplot2 call if you want to be able to use rownames(G).
Set data=as.data.frame(G) in your call to geom_text.
p <- p + geom_text(aes(label = row.names(G)), size = 3, vjust = 1.25, colour = "black")
You're providing it with a layer, but no data to plot. Either move label=
into your original call to ggplot or provide geom_text()
with a data=
argument
Your version in the function is missing the following two lines at the very beginning compared to the original version:
Data$Env <- factor(Data$Block)
Data$Gen <- factor(Data$Variety)
Have you experimented with using debug()
to step through functions to find the source of errors?