googleVis/ 0000755 0001762 0000144 00000000000 13032171320 012200 5 ustar ligges users googleVis/inst/ 0000755 0001762 0000144 00000000000 13032146654 013171 5 ustar ligges users googleVis/inst/mansections/ 0000755 0001762 0000144 00000000000 12737123564 015522 5 ustar ligges users googleVis/inst/mansections/GoogleChartToolsURLConfigOptions.txt 0000644 0001762 0000144 00000000144 12737123564 024566 0 ustar ligges users \url{https://developers.google.com/chart/interactive/docs/gallery/CHARTNAME#Configuration_Options}
googleVis/inst/mansections/gvisOutputStructure.txt 0000644 0001762 0000144 00000002634 12737123564 022402 0 ustar ligges users "\code{gvis}" and "\code{list}".
An object of class "\code{gvis}" is a list containing at least the
following components:
\describe{
\item{\code{type}}{Google visualisation type}
\item{\code{chartid}}{character id of the chart object. Unique chart
ids are required to place several charts on the same page.
}
\item{\code{html}}{a list with the building blocks for a page
\describe{
\item{\code{header}}{a character string of a html page header:
\code{...
},}
\item{\code{chart}}{a named character vector of the chart's building blocks:
\describe{
\item{\code{jsHeader}}{Opening \code{}.
}
\item{\code{jsChart}}{Call of the \code{jsDisplayChart} function.
}
\item{\code{divChart}}{\code{
} container to embed the chart
into the page.
}
}
}
\item{\code{caption}}{character string of a standard caption,
including data name and chart id.
}
\item{\code{footer}}{character string of a html page footer:
\code{...}, including the used R and googleVis version
and link to Google's Terms of Use.}
}}
}
googleVis/inst/mansections/gvisOptions.txt 0000644 0001762 0000144 00000004375 12737123564 020620 0 ustar ligges users The parameters can be set via a named list. The parameters have to map those
of the Google documentation.
\itemize{
\item{Boolean arguments are set to
either \code{TRUE} or \code{FALSE}, using the R syntax.
}
\item{Google API parameters with a single value and with names that don't
include a "." are set like one would do in R, that is
\code{options=list(width=200, height=300)}.
Exceptions to this rule are the width and height options for
\code{\link{gvisAnnotatedTimeLine}} and \code{\link{gvisAnnotationChart}}.
For those two functions, width and height must be character strings of the
format \code{"Xpx"}, where \code{X} is a number, or \code{"automatic"}.
For example,
\code{options=list(width="200px", height="300px")}.
}
\item{Google API parameters with names that don't include a ".", but require
multivalues are set as a character, wrapped in "[ ]" and separated by commas,
e.g.
\code{options=list(colors="['#cbb69d', '#603913', '#c69c6e']")}
}
\item{Google API parameters with names that do include a "." present parameters with
several sub-options and have to be set as a character wrapped in "{ }".
The values of those sub-options are set via parameter:value. Boolean values
have to be stated as \code{'true'} or \code{'false'}.
For example the Google documentaion states the formating options for the
vertical axis and states the parameter as \code{vAxis.format}.
Then this paramter can be set in R as:
\code{options=list(vAxis="{format:'#,###\%'}")}.
}
\item{If several sub-options have to be set, e.g.
\code{titleTextStyle.color}, \code{titleTextStyle.fontName} and
\code{titleTextStyle.fontSize}, then those can be combined in one list item
such as:
\code{options=list(titleTextStyle="{color:'red', fontName:'Courier', fontSize:16}")}
}
\item{paramters that can have more than one value per sub-options are
wrapped in "[ ]". For example to set the labels for left and right axes use:
\code{options=list(vAxes="[{title:'val1'}, {title:'val2'}]")}
}
\item{\code{gvis.editor}}{ a character label for an
on-page button that opens an in-page dialog box enabling
users to edit, change and customise the chart. By default no
value is given and therefore no button is displayed.
}
}
For more details see the Google API documentation and the R examples below.
googleVis/inst/mansections/GoogleChartToolsURL.txt 0000644 0001762 0000144 00000000115 12737123564 022062 0 ustar ligges users \url{http://developers.google.com/chart/interactive/docs/gallery/CHARTNAME}
googleVis/inst/CITATION 0000644 0001762 0000144 00000001274 13032144216 014322 0 ustar ligges users citHeader("To cite the googleVis package in publications use:")
citEntry(entry="Article",
title = "googleVis: Interface between R and the Google Visualisation API",
author = personList(as.person("Markus Gesmann"), as.person("Diego de Castillo")),
journal = "The R Journal",
year = 2011,
volume = 3,
number = 2,
pages = "40--44",
month = "December",
url= "https://journal.r-project.org/archive/2011-2/RJournal_2011-2_Gesmann+de~Castillo.pdf",
textVersion =
paste("Markus Gesmann and Diego de Castillo.",
"Using the Google Visualisation API with R.",
"The R Journal, 3(2):40-44, December 2011."))
googleVis/inst/gadgets/ 0000755 0001762 0000144 00000000000 12737123564 014615 5 ustar ligges users googleVis/inst/gadgets/gadgets.R 0000644 0001762 0000144 00000014632 12737123564 016364 0 ustar ligges users ## Move into the inst/gadget folder before you run this script!
Motion=gvisMotionChart(Fruits, idvar="Fruit", timevar="Year",
options=list(height=350, width=400))
cat(createGoogleGadget(Motion), file="motionchart.xml")
## Geo Map with coloured regions
Geo=gvisGeoMap(Exports, locationvar="Country", numvar="Profit",
options=list(dataMode='regions'))
cat(createGoogleGadget(Geo), file="geomap.xml")#
## Show Hurricane Andrew (1992) storm track with Geo Map
AndrewGeo <- gvisGeoMap(Andrew, locationvar="LatLong", numvar="Speed_kt",
hovervar="Category",
options=list(height=250, width=400, region="US"))
cat(createGoogleGadget(AndrewGeo), file="andrewgeomap.xml")
## Hurricane Andrew (1992) storm track with Google Maps
AndrewMap <- gvisMap(Andrew, "LatLong" , "Tip",
options=list(showTip=TRUE, showLine=TRUE, enableScrollWheel=TRUE,
mapType='terrain', useMapTypeControl=TRUE))
cat(createGoogleGadget(AndrewMap), file="andrewmap.xml")
## Geo Chart
GeoChart <- gvisGeoChart(Exports, "Country", "Profit",
options=list(region="150"))
cat(createGoogleGadget(GeoChart), file="geochart.xml")
## Table. Click on the column header to sort the rows
Table <- gvisTable(Exports, options=list(width=400, height=270))
cat(createGoogleGadget(Table), file="table.xml")
## Table with embedded links
PopTable <- gvisTable(Population, options=list(width=600, height=300, page='enable'))
cat(createGoogleGadget(PopTable), file="poptable.xml")
## Tree Map. Left mouse-click to drill down, right mouse-click to move up a hierarchy
Tree <- gvisTreeMap(Regions, "Region", "Parent", "Val", "Fac",
options=list(fontSize=16, width=400, height=300))
cat(createGoogleGadget(Tree), file="treemap.xml")
require(datasets)
states <- data.frame(state.name, state.area)
states3 <- data.frame(state.region, state.division, state.name, state.area)
regions <- aggregate(list(region.area=states3$state.area),
list(region=state.region), sum)
divisions <- aggregate(list(division.area=states3$state.area),
list(division=state.division, region=state.region),
sum)
my.states3 <- data.frame(regionid=c("USA",
as.character(regions$region),
as.character(divisions$division),
as.character(states3$state.name)),
parentid=c(NA, rep("USA", 4),
as.character(divisions$region),
as.character(states3$state.division)),
state.area=c(sum(states3$state.area),
regions$region.area,
divisions$division.area,
states3$state.area))
my.states3$state.area.log=log(my.states3$state.area)
statesTree3 <- gvisTreeMap(my.states3, "regionid", "parentid",
"state.area", "state.area.log", options=list(showScale=TRUE, width=400, height=300))
cat(createGoogleGadget(statesTree3), file="statestreemap.xml")
## Annotated Time Line Chart
AnnoTimeLine <- gvisAnnotatedTimeLine(Stock, datevar="Date",
numvar="Value", idvar="Device",
titlevar="Title", annotationvar="Annotation",
options=list(displayAnnotations=TRUE,
legendPosition='newRow',
width=400, height=250)
)
cat(createGoogleGadget(AnnoTimeLine), file="annotimeline.xml")
## Sample data
df=data.frame(country=c("US", "GB", "BR"), val1=c(1,3,4), val2=c(23,12,32))
## Line chart
Line <- gvisLineChart(df,
options=list(legend='none', width=300, height=200))
cat(createGoogleGadget(Line), file="linechart.xml")
## Bar chart
Bar <- gvisBarChart(df,
options=list(legend='none', width=300, height=200))
cat(createGoogleGadget(Bar), file="barchart.xml")
## Column chart
Column <- gvisColumnChart(df,
options=list(legend='none', width=300, height=200))
cat(createGoogleGadget(Column), file="columnchart.xml")
## Area chart
Area <- gvisAreaChart(df,
options=list(legend='none', width=300, height=300))
cat(createGoogleGadget(Area), file="areachart.xml")
## Stepped Area Chart
SteppedArea <- gvisSteppedAreaChart(df, xvar="country", yvar=c("val1", "val2"),
options=list(isStacked=TRUE, width=300, height=290))
plot(SteppedArea)
cat(createGoogleGadget(Area), file="steppedareachart.xml")
## Scatter chart
Scatter <- gvisScatterChart(women, options=list(legend="none",
lineWidth=2, pointSize=0,
title="Women", vAxis="{title:'weight (lbs)'}",
hAxis="{title:'height (in)'}", width=300, height=300))
cat(createGoogleGadget(Scatter), file="scatterchart.xml")
## Bubble chart
Bubble <- gvisBubbleChart(Fruits, idvar="Fruit", xvar="Sales", yvar="Expenses",
colorvar="Year", sizevar="Profit",
options=list(hAxis='{minValue:75, maxValue:125}',
width=500, height=300))
cat(createGoogleGadget(Bubble), file="bubblechart.xml")
## Pie chart
Pie <- gvisPieChart(CityPopularity,
options=list(width=400, height=200))
cat(createGoogleGadget(Pie), file="piechart.xml")
## Gauge
Gauge <- gvisGauge(CityPopularity, options=list(min=0, max=800, greenFrom=500,
greenTo=800, yellowFrom=300, yellowTo=500,
redFrom=0, redTo=300, width=300, height=220))
cat(createGoogleGadget(Gauge), file="gauge.xml")
## Intensity Map
Intensity <- gvisIntensityMap(df)
cat(createGoogleGadget(Intensity), file="intensitymap.xml")
## Org chart
Org <- gvisOrgChart(Regions, options=list(width=600, height=210,
size='large', allowCollapse=TRUE))
cat(createGoogleGadget(Org), file="orgchart.xml")
## Candlestick chart
Candle <- gvisCandlestickChart(OpenClose, xvar="Weekday", low="Low",
open="Open", close="Close",
high="High",
options=list(legend='none',
width=300, height=250))
cat(createGoogleGadget(Candle), file="candlestickchart.xml")
googleVis/inst/rsp/ 0000755 0001762 0000144 00000000000 12737123564 014003 5 ustar ligges users googleVis/inst/rsp/index.rsp 0000644 0001762 0000144 00000013676 12737123564 015655 0 ustar ligges users
<%title="Using the Google visualisation API with R"%>
<%@include file="src/simpleHead.rsp"%>
<%@include file="src/simpleHeader.rsp"%>
<%require(googleVis)%>
googleVis is a package
for R which provides
functions to visualise data in R with
the Google
Visualisation API.
Please read
Google's terms
of use and data policy.
The visual output will be rendered in your browser using Flash.
Type ?googleVis in the R console to see the overall documentation
and vignette('googleVis') to access the package
vignette.
This page provides some examples of the package. You find more
as part of the demo; to execute the demo type into the R
console: demo(googleVis).
Embedding googleVis charts into your web page with R.rsp
The R
package R.rsp
provides a lightweight web-server which we are using here to
display these pages. Additionally the R.rsp
package allows us to dynamically generate documents into
static content using R Server Pages. This means we can mix html and R
code to create content on the fly.
<%=gvisMap(as.list(Andrew), "LatLong" , "Tip", options=list(showTip=TRUE, showLine=TRUE, enableScrollWheel=TRUE, mapType='terrain', useMapTypeControl=TRUE))$html$chart%>
See also: Google
Map API
<%=gvisTreeMap(Regions, "Region", "Parent", "Val", "Fac", options=list(width=600, height=500, showScale=TRUE, fontSize=16))$html$chart%>
See also: Google
Tree Map API
<%=gvisAnnotatedTimeLine(Stock, datevar="Date", numvar="Value", idvar="Device", titlevar="Title", annotationvar="Annotation", options=list(displayAnnotations=TRUE, width=600, height=350))$html$chart%>
See also: Google
Annotated Time Line API
We hope these examples show you how you can generate content
with functions from the googleVis
packages.
If a page is loading "forever", that is, the internal web server seems to be stuck, try to press ENTER in the main R window. This normally helps.
<%@include file="src/simpleFooter.rsp"%>
googleVis/inst/rsp/src/ 0000755 0001762 0000144 00000000000 13032146660 014561 5 ustar ligges users googleVis/inst/rsp/src/simpleHeader.rsp 0000755 0001762 0000144 00000001372 12737123564 017730 0 ustar ligges users <%-- H e a d e r --%>
<%
uri <- getRequestUri(request);
uriPath <- strsplit(uri, split="/")[[1]][-1];
if (regexpr("./$", uri) != -1) {
upPath <- "../";
} else if (regexpr("./index.rsp$", uri) != -1) {
upPath <- "../";
uriPath <- uriPath[-length(uriPath)];
} else {
upPath <- "index.rsp";
uriPath <- uriPath[-length(uriPath)];
}
%>
~ /
<% for (kk in seq(length=length(uriPath))) { %>
/"><%=uriPath[kk]%> /
<% } %>
<%@include file="../src/simpleFooter.rsp"%>
googleVis/inst/shiny/ 0000755 0001762 0000144 00000000000 12737123564 014331 5 ustar ligges users googleVis/inst/shiny/ui.R 0000644 0001762 0000144 00000000347 12737123564 015075 0 ustar ligges users shinyUI(pageWithSidebar(
headerPanel("googleVis on Shiny"),
sidebarPanel(
selectInput("dataset", "Choose a dataset:",
choices = c("rock", "pressure", "cars"))
),
mainPanel(
htmlOutput("view")
)
)) googleVis/inst/shiny/server.R 0000644 0001762 0000144 00000000541 12737123564 015762 0 ustar ligges users library(googleVis)
shinyServer(function(input, output) {
datasetInput <- reactive({
switch(input$dataset,
"rock" = rock,
"pressure" = pressure,
"cars" = cars)
})
output$view <- renderGvis({
gvisScatterChart(datasetInput(),
options=list(title=paste('Data:',input$dataset)))
})
}) googleVis/inst/doc/ 0000755 0001762 0000144 00000000000 13032146654 013736 5 ustar ligges users googleVis/inst/doc/googleVis.Rnw 0000644 0001762 0000144 00000154150 13032146654 016372 0 ustar ligges users \documentclass{article}
\usepackage[T1]{fontenc}
\usepackage{Sweave}
\usepackage{thumbpdf}
\usepackage{url}
%\usepackage{wrapfig}
\usepackage{hyperref}
\hypersetup{
pdftitle={Introduction to googleVis},%
pdfauthor={Markus Gesmann},%
}
%\VignetteEngine(Sweave)
%!\VignetteEncoding{UTF-8}
%\VignetteIndexEntry{Introduction to googleVis}
%\VignetteDepends{googleVis}
%\VignetteKeywords{google, visualisation, api}
%\VignettePackage{googleVis}
\SweaveOpts{engine=R, eps=FALSE, keep.source = TRUE}
<>=
options(prompt = "R> ", digits = 4, show.signif.stars = FALSE)
@
%\keywords{google, visualisation, api, \proglang{R}}
\setlength{\parindent}{0.0in}
\setlength{\parskip}{2mm}
\newcommand{\googleVis}{\textbf{\texttt{googleVis}} }
\newcommand{\knitr}{\textbf{\texttt{knitr}} }
\newcommand{\rsp}{\textbf{\texttt{R.rsp }}}
\newcommand{\brew}{\textbf{\texttt{brew }}}
\newcommand{\rapache}{\emph{{RApache }}}
\newcommand{\Rook}{\emph{{Rook }}}
\newcommand{\shiny}{\textbf{\texttt{shiny }}}
\renewcommand{\familydefault}{\sfdefault}
\begin{document}
\SweaveOpts{concordance=TRUE}
\author{Markus Gesmann\footnote{markus.gesmann@gmail.com},
Diego de Castillo\footnote{decastillo@gmail.com}}
\title{Introduction to googleVis \Sexpr{packageDescription("googleVis")[['Version']]}
}
\maketitle
\begin{abstract}
The \googleVis package provides an interface between R and the
Google Charts API. Google Charts offer interactive
charts which can be embedded into web pages. The best
known of these charts is probably the Motion Chart, popularised
by Hans Rosling in his TED talks.
The functions of the \googleVis package allow the user to visualise
data stored in R data frames with Google Charts
without uploading the data to Google. The output of a \googleVis
function is HTML code that contains the data and references to
JavaScript functions hosted by Google.
googleVis makes use of the internal R HTTP server to display the
output locally. A modern browser with an Internet connection is
required and for some charts a Flash player.
\end{abstract}
\clearpage
\tableofcontents
\clearpage
\section{Introduction}\label{sec:Intro}
\subsection{Motivation}\label{sec:Motivation}
More and more data is becoming available, and yet
stories and insights are still often missed: we are lost in the data
jungle and struggle to see the wood for the trees.
Hence, new tools are required to bring data to life, to engage with
users, to enable them to slice and dice the data, to view it from
various angles and to find stories worth telling: outliers, trends or
even the obvious.
In 2006 Hans Rosling gave an inspiring talk at
TED~\cite{HansRoslingTedTalk} about social and economic developments
in the world over the past 50 years, which challenged the views and
perceptions of many listeners. Rosling had used extensive data analysis
to reach his conclusions. To visualise his talk, he and his team at
Gapminder~\cite{Gapminder} had developed animated bubble charts, aka
motion charts, see Figure~\ref{MotionChartGUI}.
Rosling's presentation popularised the idea and use of interactive
charts. One year later the software behind
Gapminder was bought by Google and integrated as motion charts into
their Google Charts API~\cite{GoogleVisApi}, formerly known as Google
Visualisation API.
In 2010 Sebasti\'{a}n P\'{e}rez Saaibi~\cite{Saaibi2010} presented at the
R/Rmetrics Workshop on Computational Finance and Financial
Engineering, the idea to use Google motion charts to visualise R
output with the \rsp package~\cite{Rsp}.
Inspired by those talks and the desire to use interactive data
visualisation tools to foster the dialogue between data analysts and
others the authors of this vignette started the development of the
\googleVis package~\cite{googleVis},
\cite{RJournal:2011-2:GesmannCastillo} in August 2010.
\begin{figure}[t]
\begin{center}
\includegraphics[width=\textwidth]{./figures/MotionChart.pdf}
\caption{
Overview of a Google Motion Chart. Screenshot of the output of
\texttt{plot(gvisMotionChart(Fruits, idvar='Fruit', timevar='Year'))}
}\label{MotionChartGUI}
\end{center}
\end{figure}
%\clearpage
\subsection{Google Chart Tools}\label{sec:GoogleChartTools}
The Google Charts API~\cite{GoogleVisApi}
allows users to create interactive charts as part of Google
documents, spreadsheets and web pages. In this text, we will focus
on the usage of the API as part of web pages.
The Google Public Data Explorer~\cite{GooglePublicData} provides a
good example, demonstrating the use of interactive charts and how they can
help to analyse data. Please note, that all of those charts are
rendered by the browser.
The charting data can either be embedded into the HTML file or read
dynamically. The key to the Google Charts is that the data is
structured in a DataTable~\cite{DataTable}, and this is where the \googleVis
package helps, as it transforms R data frames into JSON~\cite{json}
objects, using the \texttt{\textbf{jsonlite}} package~\cite{jsonlite}, as
the basis for a DataTable.
As an example we shall look at the html-code of a motion chart from
Google's visualisation gallery~\cite{GoogleMotionChart}, which
generates output similar to Figure~\ref{MotionChartGUI}:
\begin{small}\label{motionchartcodeexample}
\begin{verbatim}
1
2
3
6
30
31
32
34
35
36
\end{verbatim}
\end{small}
The code and data are processed and rendered by the browser and is
not submitted to any server\footnote{\url{https://google-developers.appspot.com/chart/interactive/docs/gallery/motionchart.html\#Data\_Policy}}.
You will notice that the above HTML code has five generic
parts\footnote{For more details see
\url{https://google-developers.appspot.com/chart/interactive/docs/index}}:
\begin{itemize}
\item references to Google's AJAX (l. 4) and Visualisation
API (ll. 7 -- 8),
%%shown here as \verb=jsapi= and \verb='motionchart'=,
\item data to visualise as a \verb=DataTable= (ll. 11 -- 24),
\item an instance call to create the chart (ll. 25 -- 26),
\item a method call to draw the chart including options, shown
here as width and height (l. 27),
\item an HTML \verb=
= element to add the chart to the page (ll.
32 -- 34).
\end{itemize}
These principles hold true for most of the interactive charts of the
Google Chart Tools, see the examples in Figure~\ref{demos}.
However, before you use the API you should read the \href{https://developers.google.com/terms/}{Google
Terms of Service}~\cite{GoogleTerms}.
\section{The \googleVis package}\label{sec:googleVisPackage}
The \googleVis package provides an interface between R and the Google
Chart Tools. The functions of the package allow the user to
visualise data stored in R data frames with Google Charts.
Version (\Sexpr{packageDescription("googleVis")[['Version']]}) of the package
provides interfaces to Motion Charts, Annotated Time Lines,
Maps, Geo Maps, Geo Charts, Intensity Maps, Tables, Gauges,
Tree Maps, further Line, Bar, Bubble, Column, Area, Stepped Area,
Combo, Scatter, Candlestick, Pie, Sankey, Annotation,
Histogram, Timeline, Calendar and Org Charts; see
Figure~\ref{demos} for some examples.
The output of a \googleVis function is HTML code that contains the
data and references to JavaScript functions hosted by Google. A
browser with an Internet connection is required to view
the output, and for Motion Charts, Geo Maps, and Annotated Time Lines
also Flash. For Geo Maps and Annotated Time Lines HTML5 alternatives are available with Geo Charts and Annotation Charts.
<>=
## Code for screen shot
MC <- gvisMotionChart(Fruits, "Fruit", "Year", options=list(width=500, height=300))
ATL <- gvisAnnotatedTimeLine(Stock, datevar="Date",
numvar="Value", idvar="Device",
titlevar="Title", annotationvar="Annotation",
options=list(
width=300, height=300,
fill=10, displayExactValues=TRUE,
colors="['#0000ff','#00ff00']")
)
Map <- gvisMap(Andrew, "LatLong" , "Tip",
options=list(showTip=TRUE, showLine=TRUE, enableScrollWheel=TRUE,
mapType='terrain', useMapTypeControl=TRUE,
width=400, height=200))
Geo <- gvisGeoMap(Exports, locationvar='Country', numvar='Profit',
options=list(dataMode="regions", width=400,height=200))
## Table with enabled paging
Table <- gvisTable(Population, options=list(page='enable', height=200, width=500))
Tree <- gvisTreeMap(Regions, "Region", "Parent", "Val", "Fac",
options=list(width=300, height=200,
fontSize=16,
minColor='#EDF8FB',
midColor='#66C2A4',
maxColor='#006D2C',
headerHeight=20,
fontColor='black',
showScale=TRUE))
M <- gvisMerge(gvisMerge(gvisMerge(MC, ATL, TRUE, tableOptions="cellspacing=10"),
gvisMerge(Map, Geo, TRUE, tableOptions="cellspacing=10")),
gvisMerge(Table, Tree, TRUE, tableOptions="cellspacing=10"))
plot(M)
@
\begin{figure}[t]
\begin{center}
\includegraphics[width=\textwidth]{./figures/googleVisDemoPlots.pdf}
\caption{
Screenshot of some of the outputs of \texttt{demo(googleVis)}.
Clockwise from top left:
\texttt{gvisMotionChart}, \texttt{gvisAnnotatedTimeLine},
\texttt{gvisGeoMap}, \texttt{gvisTreeMap}, \texttt{gvisTable}, and \texttt{gvisMap}.
}\label{demos}
\end{center}
\end{figure}
\subsection{Installation}\label{sec:Installation}
You can install \googleVis in the usual way from CRAN, e.g.:
<>=
install.packages('googleVis')
@
The installation was successful if the
command \texttt{library(googleVis)} gives you the following message:
<>=
library(googleVis)
@
<>=
library(googleVis)
@
<>=
cat(googleVis:::gvisWelcomeMessage())
@
\subsection{Using the \googleVis package}\label{sec:UsingGoogleVis}
The individual functions of the \googleVis package are documented in
the help pages. Here we will cover only the principles of
the package.
As an example, we will show how to generate a motion chart as displayed in
Figure~\ref{MotionChartGUI}. It works similarly for the other
APIs. Further examples are covered in the demos\footnote{See
\texttt{demo(package="googleVis")} for a list of the available demos.} of the \googleVis
package.
The design of the visualisation functions is fairly generic. The name
of the visualisation function is \texttt{'gvis' + ChartType}. So for
the Motion Chart we have:
\begin{verbatim}
gvisMotionChart(data, idvar='id', timevar='date',
options=list(), chartid)
\end{verbatim}
Here \texttt{data} is the input \texttt{data.frame} and \texttt{idvar}
and \texttt{timevar} specify the column names of the id variable and
time variable for the plot, while display options are set in an
optional list, which we discuss in more detail on
page~\pageref{settingoptions}. The options and data requirements
follow those of the Google Charts API and are documented in the
help pages, see
<>=
help('gvisMotionChart')
@
\begin{figure}%{r}{0.35\textwidth}
\begin{center}
\includegraphics[width=0.34\textwidth]{./figures/gvisObject.pdf}
\caption{Schematic structure of a gvis list object.
}\label{gvisObject}
\end{center}
\end{figure}
The argument \texttt{chartid} allows the user to set a chart id of the
output chart manually. If the argument is missing a random id using
\texttt{tempfile(pattern=\textquotesingle\textquotesingle)}
will be generated. Unique chart ids are required to place more than
one chart on a web page.
The output of a \googleVis function is a list of lists (a nested list)
containing information about the chart type, chart id and the HTML
code in a sub-list with header, chart, caption and footer, see Figure~\ref{gvisObject}.
The idea behind this concept is that users can get a
complete web page, while at the same time offer a facility to extract
specific parts, such as the chart itself.
This is particularly helpful if the package functions
are used in solutions where the user wants to feed the visualisation
output into other sites, or would like to embed them into rsp-pages
(see page~\pageref{rspexample}), use \rapache (see
page~\pageref{rapacheexample}) or Google Gadgets.
The output of a \googleVis function will be of class \texttt{'gvis'}
and \texttt{'list'}. Generic print (\texttt{print.gvis}) and plot
(\texttt{plot.gvis}) functions exist to ease the handling of such objects.
To illustrate the concept we shall create a motion chart using the
\texttt{Fruits} data set.
\subsection{Motion Chart Example}\label{sec:MotionChartExample}
Following the documentation of the Google Motion Chart API we need a
data set which has at least four columns: one identifying the
variable we would like to plot, one time variable and at least two
numerical variables, further numerical and character columns are allowed.
As an example we use the \texttt{Fruits} data set:
<<>>=
data(Fruits)
Fruits
@
Here we will use the columns \texttt{'Fruit'} and
\texttt{'Year'} as id and time variable respectively. However we could
have used \texttt{'Date'} instead of \texttt{'Year'} as well.
<<>>=
M <- gvisMotionChart(Fruits, idvar="Fruit", timevar="Year")
@
The structural output of \texttt{gvisMotionChart} is a list of lists as
described above
<>=
str(M)
@
<>=
## This statement avoids truncation
cat(paste(substring( capture.output( str(M) ) , 0, 66), sep="\n", collapse="\n"))
@
The first two items of the list contain information about the chart type
used and the individual chart id: %generated at run time from the chart
%type and \texttt{tempfile(pattern=\textquotesingle\textquotesingle)}:
<<>>=
M$type
M$chartid
@
The html output is a list with header, chart, caption and
footer. This allows the user to extract only certain parts
of the page, or to create a complete html page.
The header part of the html page has only basic html and formatting tags:
<<>>=
print(M, tag='header')
@
Here we used the \texttt{print} statement with the tag
\texttt{'header'} instead of \texttt{M\$html\$header} to achieve
a formatted screen output. This is the same output as
\texttt{cat(M\$html\$chart)}.
The actual Google visualisation code is stored with the data
as a named character vector in the \texttt{chart} item of the HTML
list. The chart is made up of several JavaScript and HTML
statements. Please notice that the JavaScript functions are
uniquely named with the information of the chart id.
This concept allows the user get all the chart code directly or only
specific parts; see the examples in the help page of \texttt{print.gvis}
for more details.
<<>>=
names(M$html$chart)
@
The complete chart can be displayed via:
<<>>=
print(M, tag='chart') ## or cat(M$html$chart)
@
Similarly you can also access specific components of the chart, e.g. (output truncated)
<>=
cat(M$html$chart['jsChart']) # or print(M, 'jsChart')
@
<>=
cat(paste(substring( capture.output( cat(M$html$chart['jsChart']) ) , 0, 66), sep="\n", collapse="\n"))
@
A basic chart caption and html footer are the final items of the html
list (output truncated):
<>=
print(M, tag='caption')
@
<>=
cat(paste(substring( capture.output( cat(M$html$caption) ) , 0, 66), sep="\n", collapse="\n"))
@
<>=
print(M, tag='footer')
@
<>=
cat(paste(substring( capture.output( cat(M$html$footer) ) , 0, 66), sep="\n", collapse="\n"))
@
\subsection{Displaying \texttt{gvis} objects
locally}\label{sec:DisplayLocally}
To display the page locally, type:
<>=
plot(M) # returns invisibly the file name
@
The plot method for \texttt{gvis}-objects creates HTML files in a temporary folder using
the type and chart id information of the object and it will display
the output using the R HTTP help web server locally, usually under
http://127.0.0.1.
Note that the chart caption provides a link to the chart code via
the chart id for copy and paste.
The R command \texttt{tempdir()} will show you the path of the
per-session temporary directory, in which the files were written.
You can write the chart into a local html file via the \texttt{print}
command with the file argument, e.g.
<>=
print(M, file="myGoogleVisChart.html")
@
Please note that Flash charts\footnote{Currently the following charts
require Flash: motion chart, geo map and
annotated time line} may not work when loaded as a local file
due to security settings, and therefore require to be displayed via a
web server. However, you can overcome this issue by changing your Flash security
settings. Tony Breyal posted the following solution on
\href{http://stackoverflow.com/questions/8009825/cannot-view-gvismotionchart-from-printed-html-file
}{stackoverflow.com}:
\begin{enumerate}\label{breyal}
\item Go to \url{http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04.html}
\item Click on the dropbox which says 'Edit location' and choose 'add location'
\item Click 'browse for folder'
\item Choose the folder in which you saved your HTML file
\item Click OK
\end{enumerate}
Now open your \googleVis HTML file and it should display
successfully.
Alternatively use the function \texttt{plot.gvis} explicitly,
e.g. suppose your html file is stored in
\texttt{/Users/JoeBloggs/myGoogleVisChart.html}. Using the
\texttt{plot.gvis} the file will be copied into a temporary directory
and displayed via the R HTTP help server with, in the same way as a
gvis-object:
<>=
plot.gvis("/Users/JoeBloggs/myGoogleVisChart.html")
@
Please note that this feature of \texttt{plot.gvis} was introduced
to \googleVis with version 0.3.2.
\subsection{Setting default behaviour of \texttt{print.gvis} and
\texttt{plot.gvis}}\label{sec:Options}
In \googleVis version 0.3.2 the function \texttt{plot.gvis} gained the
same argument as \texttt{print.gvis}: \texttt{tag}. By default the
\texttt{tag} argument is set to \texttt{NULL} in \texttt{plot.gvis}
and the plot function will display its output in a browser
window. However, if \texttt{tag} is not \texttt{NULL} the function
\texttt{plot.gvis} will behave exactly like \texttt{print.gvis}.
The default \texttt{tag} can be set for both functions globally via
the \texttt{options()} function. On package load \googleVis sets
\texttt{options(gvis.print.tag='html')} and
\texttt{options(gvis.plot.tag=NULL)}.
Suppose you would set \texttt{options(gvis.plot.tag='chart')} then all
following plot statements would print the chart part of the
gvis-object only, without opening a browser window. This might
seem a bit odd at first, yet it becomes helpful when you write R
Markdown files for \knitr or files for other packages such as
\textbf{\texttt{R.rsp}}.
While you draft your file you may want to see the output of \googleVis
in an interactive way, so you set \texttt{options(gvis.plot.tag=NULL)}
at the top of the file and you change the setting to \texttt{'chart'}
before you parse the file, say with \textbf{\texttt{knitr}}. This will
ensure that all plot statements return the HTML code of the chart,
rather than opening browser windows. Section~\ref{sec:knitr} on
page~\pageref{sec:knitr} provides more details and a little \knitr
example.
\subsection{Combining charts with \texttt{gvisMerge}}\label{gvisMerge}
The function \texttt{gvisMerge} takes two \texttt{gvis}-objects
and merges the underlying components into one page. The charts are
aligned either horizontally or vertically next to each other in an HTML table.
\begin{figure}[ht]
\begin{center}
\includegraphics[width=0.8\textwidth]{./figures/gvisMerge.pdf}
\caption{
Three charts combined with \texttt{gvisMerge}.
}\label{gvisMerge}
\end{center}
\end{figure}
The output of \texttt{gvisMerge} is a \texttt{gvis}-object again.
This allows us to apply the same function iteratively to create more complex
chart layouts. The following example, see Figure~\ref{gvisMerge}, aligns a geo chart
and table below each other, and combines the output with a motion chart to the right:
<<>>=
G <- gvisGeoChart(Exports, "Country", "Profit",
options=list(width=200, height=100))
T <- gvisTable(Exports,
options=list(width=200, height=270))
M <- gvisMotionChart(Fruits, "Fruit", "Year",
options=list(width=400, height=370))
GT <- gvisMerge(G,T, horizontal=FALSE)
GTM <- gvisMerge(GT, M, horizontal=TRUE,
tableOptions="bgcolor=\"#CCCCCC\" cellspacing=10")
@
<>=
plot(GTM)
@
\subsection{Setting options}\label{settingoptions}
Setting the various options of a \googleVis objects can be a bit
cumbersome at first. The options follow those of the Google
Charts API and can be set via a named list using the argument \texttt{options}.
In the following example, we create a line chart and set various
options\footnote{Please refer to the help file of the individual
\googleVis functions, as the options can vary from chart to chart.},
see the output in Figure~\ref{Options}.
\begin{figure}[ht]
\begin{center}
\includegraphics[width=0.8\textwidth]{./figures/Options.pdf}
\caption{
A line chart with various options set.
}\label{Options}
\end{center}
\end{figure}
<>=
df <- data.frame(country=c("US", "GB", "BR"),
val1=c(1,3,4), val2=c(23,12,32))
Line <- gvisLineChart(df, xvar="country", yvar=c("val1","val2"),
options=list(
title="Hello World",
titleTextStyle="{color:'red',
fontName:'Courier',
fontSize:16}",
backgroundColor="#D3D3D3",
vAxis="{gridlines:{color:'red', count:3}}",
hAxis="{title:'Country', titleTextStyle:{color:'blue'}}",
series="[{color:'green', targetAxisIndex: 0},
{color: 'orange',targetAxisIndex:1}]",
vAxes="[{title:'val1'}, {title:'val2'}]",
legend="bottom",
curveType="function",
width=500,
height=300
))
plot(Line)
@
As you can see from the example above, the simpler options can be set by name=value,
e.g. width=500, while the more complex options with sub-components are
listed in curly brackets \{\}, and arrays, e.g. to define the two
axes, use square brackets [ ].
Generally, the following rules apply:
\begin{itemize}
\item parameters with names that do not include a "." are set with a single
value, e.g. width and height. Those are set like one would do in R, that is
\texttt{options=list(}\texttt{width=200,} \texttt{height=300)}.
Boolean arguments are set to
either \texttt{TRUE} or \texttt{FALSE}, using the R syntax.
\item parameters with names that do not include a "." and are set with
multiple values, e.g. \texttt{color}, and are wrapped in "[ ]", e.g.
\texttt{options=list(} \texttt{colors="['\#cbb69d',} \texttt{'\#603913',}
\texttt{'\#c69c6e']")}
\item parameters with names that do include a "." present parameters with
several sub-options and have to be set as a string wrapped in "\{ \}".
The values of those sub-options are set via parameter:value. Boolean values
have to be stated as \texttt{'true'} or \texttt{'false'}.
For example the Google documentaion states the formating options for the
vertical axis and states the parameter as \texttt{vAxis.format}.
Then this paramter can be set in R as:
\texttt{options=list(} \texttt{vAxis="\{format:'\#,\#\#\#\%'\}")}.
\item If several sub-options have to be set, e.g.
\texttt{titleTextStyle.color,} \texttt{title\-Text\-Style.\-fontName} and
\texttt{titleTextStyle.fontSize}, then those can be combined in one list item
such as:
\texttt{options=list(} \texttt{titleTextStyle="\{color:'red',}
\texttt{fontName:'Courier',} \texttt{fontSize:16\}")}
\item paramters that can have more than one value per sub-options are
wrapped in "[ ]". For example to set the labels for left and right axes use:
\texttt{options=list(} \texttt{vAxes="[\{title:'val1'\},}
\texttt{\{title:'val2'\}]")}
\end{itemize}
The following example set the colour axis of a geo chart,
see Figure~\ref{geochart}:
<>=
Geo <- gvisGeoChart(CityPopularity, locationvar='City',
colorvar='Popularity',
options=list(region='US', height=350,
displayMode='markers',
colorAxis="{values:[200,400,600,800],
colors:[\'red', \'pink\', \'orange',\'green']}")
)
plot(Geo)
@
\begin{figure}[ht]
\begin{center}
\includegraphics[width=0.8\textwidth]{./figures/gvisGeoChart.pdf}
\caption{
A geo chart with options set for a colour axis.}
\label{geochart}
\end{center}
\end{figure}
\subsubsection{Chart Editor}
A special option for all charts is \texttt{gvis.editor}, which adds an
edit button to the page, allowing the user to edit, change and
customise the chart on the fly, see the following example and
Figure~\ref{Editor}. The content of the list item \texttt{gvis.editor}
describes the label of the browser button\footnote{See also
\url{https://google-developers.appspot.com/chart/interactive/docs/drawing\_charts\#charteditor}}.
<>=
Editor <- gvisLineChart(df, options=list(gvis.editor='Edit me!'))
plot(Editor)
@
\begin{figure}[ht]
\begin{center}
\includegraphics[width=0.8\textwidth]{./figures/Editor.pdf}
\caption{
Example of \googleVis chart with \texttt{options = list (gvis.editor =
'Edit me!')}.
}\label{Editor}
\end{center}
\end{figure}
\subsubsection{Dealing with apostrophes in column names}
The \googleVis package converts data frames into JSON objects.
The column names of the resulting JSON tables are encapsulated with
single speech marks, see lines 12 -- 16 of the code example on
page~\pageref{motionchartcodeexample}.
Hence apostrophes in column names of your input data frame have
to be encapsulated by a double backslash.
Here is a little example, see the output in Figure~\ref{fig:apostrophes}.
<<>>=
df <- data.frame("Year"=c(2009,2010), "Lloyd\\'s"=c(86.1, 93.3),
"Munich Re\\'s R/I"=c(95.3, 100.5),
check.names=FALSE)
df
CR <- gvisColumnChart(df, options=list(vAxis='{baseline:0}',
title="Combined Ratio %",
legend="{position:'bottom'}"))
@
<>=
plot(CR)
@
\begin{figure}[t]
\centering
\includegraphics[width=0.5\textwidth]{./figures/Apostrophe.pdf}
\caption{Visualising data with apostrophes in column names.}
\label{fig:apostrophes}
\end{figure}
\section{Embedding \googleVis in web sites}
\subsection{Integrating \texttt{gvis} objects in existing sites}
Suppose you have an existing web page and would like to integrate the
output of a \googleVis function, such as \texttt{gvisMotionChart}.
In this case you only need the chart output from
\texttt{gvisMotionChart}. So you can either copy and paste the output
from the R console
<>=
print(M, 'chart') ## or cat(M$html$chart)
@ or the browser, see previous section,
into your existing html page, or write the content directly into a file
<>=
print(M, 'chart', file='myfilename')
@
and process it from there.
\subsection{Using \googleVis output with WordPress}
\href{http://wordpress.org/}{WordPress} is a popular web software for
creating websites and blogs. Here we give some tips about the
usage with \googleVis output.
By default WordPress does not allow JavaScript code (and hence \googleVis
output) to be inserted into a page. However, additional plugins
allow you to extend the functions of WordPress.
One option of embedding JavaScript code inside a WordPress post is to use
the ``custom fields shortcode''
plugin\footnote{\url{http://wordpress.org/extend/plugins/custom-fields-shortcode}}.
The plugin allows you to create a custom field for the \googleVis
code, which can be referred to in your article.
Suppose you created a motion chart in R:
<>=
M <- gvisMotionChart(Fruits, "Fruit", "Year",
options=list(width=400, height=370))
@
Copy the chart code, e.g. from
<>=
print(M, 'chart')
@
and paste it into the value text area of a custom field in WordPress, e.g.
with instance name \texttt{Fruits}. To include the motion chart into your article add
\texttt{[cf]Fruits[/cf]} into the post, see Figure~\ref{wordpress} for
an illustration.
\begin{figure}[t]
\centering
\includegraphics[width=0.8\textwidth]{./figures/CreatePost.pdf}
\caption{Including \googleVis output in a WordPress blog entry.}
\label{wordpress}
\end{figure}
\subsection{Using \googleVis output with Google Sites, Blogger, etc.}
Google Charts can be used with other Google products such as Google
Sites, Blogger or Google Code wiki pages.
However, in most cases, the chart has to be embedded as a Google Gadget.
Google Gadgets are written in XML and can have HTML and Javascript components.
Here is an example of a 'Hello World' program written using Google
Gadget technology from \href{http://en.wikipedia.org/wiki/Google_Gadgets}{Wikipedia}.
\begin{verbatim}
\end{verbatim}
The \googleVis package comes with the function
\texttt{createGoogleGadget}, which takes a gvis-object and
wraps it into an XML gadget file. Here is an example with a motion chart:
<<>>=
M <- gvisMotionChart(Fruits, "Fruit", "Year")
G <- createGoogleGadget(M)
@
<>=
cat(G, file="myGadget.xml")
@
In order to use the gadget, the file \texttt{myGadget.xml} has to be
hosted online, e.g. using Google Docs.
Suppose the URL to the gadget is
\texttt{http://example.com/myGadget.xml}, than you can embed the gadget
\begin{itemize}
\item in a Google Site via the menu:
"Insert" -> "More gadgets ..." -> "Add gadget URL",
\item in a Google Code wiki via the \texttt{wiki:gadget} tag, e.g.:
\texttt{},
\item in Blogger via the design tab, see site gadgets.
\end{itemize}
However, the situation is different again, if you would like to include the \googleVis
output into a blogger post. In this case, a gadget does not
work. You can either copy and paste the chart directly into your
post, but then it does not seem to work with MS Internet Explorer, or
you use an indirect approach. This means that the \googleVis
chart has to be hosted on a separate page (e.g. in a public web
folder) and is embedded into the blog post by using the
\texttt{