As you can see from the title, I ran into a problem that already took me one entire afternoon. I have a data frame which can be accessed from here, I want to plot several columns against some other columns, a pair of columns at each time to be precise.
therefore, I create a data.frame
to store the pair of column names that I want to plot against each other:
varname.df<-data.frame(num=c(1:9),
cust= c("custEnvironment",'custCommunity','custHuman','custEmp','custDiversity',
'custProduct','custCorp',"custtotal.index","custtotal.noHC.index"),
firm=c("firmEnvironment",'firmCommunity','firmHuman','firmEmp','firmDiversity',
'firmProduct','firmCorp',"firmtotal.index","firmtotal.noHC.index"))
## factor to character
i<-sapply(varname.df,is.factor)
varname.df[i]<-lapply(varname.df[i], as.character)
rm(i)
then plot using ggplot2
and store the resultant figure in a list, see the code below:
## data I provided in the link above
temp<-read.xlsx('sample data.xlsx',1)
f <- list()
for(i in 1:9) { #dim(varname.df)[1]
# p[[i]]<-plot(x = SC.csr[,varname.df[i,'cust']],y = SC.csr[,varname.df[i,'firm']])
dat<-subset(temp,select = c(varname.df[i,'cust'], varname.df[i,'firm']))
pc1 <- ggplot(dat,aes(y = dat[,1], x = dat[,2])) +
# labs(title="Plot of CSR", x =colnames(dat)[2], y = colnames(dat)[1]) +
geom_point()
f[[i]]<-pc1
print(pc1)
Sys.sleep(5)
rm(pc1,pc2,pc3)
}
do.call(grid.arrange,f)
which suppose to work as the answer here and here, however, things just seem not that good to me since it gives me
the exact same points in all the figure, but if you run the for loop, it will literally produce different figures at each iteration as you can see with your own eyes.
After debugging nearly an afternoon, it seems like whenever I add a new ggplot
object to the list, it just changes all the data points of all other ggplot
objects in the same list.
This is so weird and frustrating in a sense that no error throwout but things are wrong somewhere out there. Any suggestion would be deeply appreciated.
-----------"EDIT"-------problem solved here, the 3rd answer.