M <- gvisMotionChart(Fruits, "Fruit", "Year")
str(M)
## The output for a complete web page
M
## Access only the plot,
M$html$chart
## wrap it in cat and it becomes more readable,
cat(unlist(M$html$chart))
## or use the print function.
print(M, "chart")
## Extract the data as a JavaScript function.
print(M, "jsData")
## Display the visualisation.
## A web browser with Internet connection and Flash is required.
plot(M)
## Combine with another chart, e.g. table
tbl <- gvisTable(Fruits, options=list(height=220))
Mtbl <- gvisMerge(M, tbl)
plot(Mtbl)
## Suppose you have an existing web page in which you embedded a
## motion chart with the id "mtnc".
## Now you have a new set of data, but you would like to avoid
## touching the html file again.
## The idea is to write the data and JavaScript functions into separate
## files and to refer to these in the html page.
## In this example we call the chart id "mtnc"
## To display the example we use the R HTTP server again, and
## write the files into a temp directory
myChartID <- "mtnc"
## baseURL should reflect your web address, e.g. http://myHomePage.com
baseURL <- sprintf("http://127.0.0.1:%s/custom/googleVis", tools:::httpdPort)
wwwdir <- tempdir() ## the www repository on you computer
## Create a motion chart
M=gvisMotionChart(Fruits, "Fruit", "Year", chartid=myChartID)
## Here is our plot again
plot(M)
## Write the data and functions into separate files:
cat(M$html$chart['jsData'], file=file.path(wwwdir, "gvisData.js"))
cat(M$html$chart[c('jsDrawChart', 'jsDisplayChart', 'jsChart')],
file=file.path(wwwdir, "gvisFunctions.js"))
## Create a html page with reference to the above
## JavaScript files
html <- sprintf('
<html>
<head>
<script type="text/javascript" src="http://www.google.com/jsapi">
</script>
<script type="text/javascript" src="%s/gvisFunctions.js"></script>
<script type="text/javascript" src="%s/gvisData.js"></script>
<script type="text/javascript">
displayChart%s()
</script>
</head>
<body>
<div id="%s" style="width: 600px; height: 500px;"></div>
</body>
</html>
', baseURL, baseURL, myChartID, myChartID)
## Write html scaffold into a file
cat(html, file=file.path(wwwdir, paste("Chart", myChartID, ".html", sep="")))
## Display the result via
URL <- paste(baseURL,"/Chart", myChartID, ".html", sep="")
browseURL(URL)
## Update the data, say the data should have shown North and South
## instead of East and West as a location
FruitsUpdate <- Fruits
levels(FruitsUpdate$Location)=c("North", "South")
Mupdate=gvisMotionChart(FruitsUpdate, "Fruit", "Year", chartid=myChartID)
## Only update the file gvisData.js:
cat(Mupdate$html$chart['jsData'], file=file.path(wwwdir, "gvisData.js"))
## Redisplay the chart with the updated data
browseURL(URL)
Run the code above in your browser using DataLab