Search code examples
rggplot2pca

Why I can't use arrow function for my plot of variables in a principal components analysis? (with ggplot2)


I trying put arrows in my plot of variables in a principal components analysis (I use PCA function of a FactoMineR library) this:

# Generate random values for the data
data<-data.frame(runif(100,0,1),rnorm(100,2,9),runif(100,0,8),rnorm(100,10,25))
pca<-PCA(data,ncp=2,graph=F)

vPC1<-pca$var$coord[,1]
vPC2<-pca$var$coord[,2]
vlabs<-rownames(pca$var$coord)
vPCs<-data.frame(cbind(vPC1,vPC2))
rownames(vPCs)<-vlabs
colnames(vPCs)<-colnames(PCs)
circleFun<-function(center=c(0,0),diameter=1,npoints=100){
  r=diameter/2
  tt<-seq(0,2*pi,length.out = npoints)
  xx<-center[1]+r*cos(tt)
  yy<-center[2]+r*sin(tt)
  return(data.frame(x=xx,y=yy))
}
dat<-circleFun(c(0,0),2.3,npoints=100)
ggplot(dat,aes(x,y))+
  geom_path()+
  geom_text(data=vPCs,aes(x=vPC1*1.1,y=vPC2*1.1,label=rownames(vPCs)),size=3)+
  coord_fixed()+
  xlab("PC1")+
  ylab("PC2")+
  geom_segment(data=vPCs,aes(x=0,y=0,xend=vPC1,yend=vPC2),arrow=arrow(length=unit(0.5,"picas")),color="grey30")

I obtain the next error:

Error in do.call("layer", list(mapping = mapping, data = data, stat = stat,  : 
  could not find function "arrow"

I don't understand if I have installed the package "graphics" that contains the function "arrow".


Solution

  • Arrow is now in the grid package so you just need to load the grid library:

    library(grid)
    

    Some of the confusion may be due to the fact that grid was loaded automatically by previous versions of ggplot (making grid functions visible/accessible to the user); now it's referred to via namespace imports instead, so you need to explicitly load grid if you want to use grid functions (or look at their help pages).