下面是gvisMotionChart的一個小接口函數,它允許除idvar和timevar外指定xvar,yvar,colorvar和sizevar的默認值。它通過簡單地改變提供的data.frame的列順序來實現這一點。該函數還將布爾變換爲數字(否則gvisMotionChart會引發錯誤)。由於我的運動圖對分析橫截面數據也非常方便,因此可以設置timevar = NULL。
# Convenience interface to gvisMotionChart that allows to set default columns
myMotionChart = function(df,idvar=colnames(df)[1],timevar=colnames(df)[2],xvar=colnames(df)[3],yvar=colnames(df)[4], colorvar=colnames(df)[5], sizevar = colnames(df)[6],...) {
library(googleVis)
# Generate a constant variable as column for time if not provided
# Unfortunately the motion plot still shows 1900...
if (is.null(timevar)) {
.TIME.VAR = rep(0,NROW(df))
df = cbind(df,.TIME.VAR)
timevar=".TIME.VAR"
}
# Transform booleans into 0 and 1 since otherwise an error will be thrown
for (i in 1:NCOL(df)) {
if (is.logical(df [,i])[1])
df[,i] = df[,i]*1
}
# Rearrange columns in order to have the desired default values for
# xvar, yvar, colorvar and sizevar
firstcols = c(idvar,timevar,xvar,yvar,colorvar,sizevar)
colorder = c(firstcols, setdiff(colnames(df),firstcols))
df = df[,colorder]
gvisMotionChart(df,idvar=idvar,timevar=timevar,...)
}
已經有答案了過去類似的問題: http://stackoverflow.com/questions/7063410/r-googlevis-problem-embedding-on-blogger http://stackoverflow.com/questions/4646779/embedding-googlevis-charts-into-a-web-site – 2012-04-21 17:14:56
感謝DWin的鏈接,但是我不能在默認變量上看到任何東西? – 2012-04-21 18:11:46