Skip to content

googleVis (embed HTML plots)

The googleVis package

The package provides an interface to Google’s chart tools, allowing users to create interactive charts based on data frames. It included maps.

The interactive maps are displayed in a browser. We can plot a complete set of interactive graphs and embed them into a web page.

Some motion charts cannot be displays in tablets and mobile phones (using HTML5) because they are rendered with Flash; Flash has to be installed on a PC.

  • Examples.
    • Charts: line, bar, column, area, stepped area, combo, scatter, bubble, customizing, candlestick (or boxplot), pie, gauge, annotation, Sankey, histogram, and motion (GapMinder-like)
    • Maps: intensity, geo, choropleth, marker, Google Maps.
    • Table, organizational chart, tree map, calendar, timeline, merging.
    • Motion charts and some maps only work in Flash, not in HTML5 as with tablets and mobile phones).
  • Gallery.
  • Documentation.
    • As above.
  • Introduction.
  • Roles.
  • Trendlines.
  • Markdown.
  • In R, run a demo with demo(googleVis).

Always cite the package:

citation("googleVis")

Suppress the message

We normally load the library…

library(googleVis)

…but we can also suppress the message when loading the package.

suppressPackageStartupMessages(library(googleVis))

Printing

  • Generate the chart.
library(googleVis)

head(Fruits, 3)

M <- gvisMotionChart(Fruits,
                     idvar='Fruit',
                     timevar='Year',
                     options=list(width=400, height=350))

# xvar =
# yvar =
# colorvar =
# sizevar =
# date.format =
  • Emulate the chart…
# In the browser, with a tag underneath
plot(M)

# In the console (code only), with a tag underneath
M

# Header part
# Basic html and formatting tags
print(M, tag='header')

# Actual Google visualization code
# Can be copy-paste in a markdown or html document
print(M, tag='chart')

# Header + visualization code = what we see in the browser

# Components of the chart
print(M, tag='jsChart')

# Basic chart caption and html footer (what is underneath)
print(M, tag='caption')

# Save it locally
print(M, file="GoogleVis/M.html")
# Or
#cat(M$html$chart, file = "GoogleVis/M.html")

Embedding a chart/map into a static website

The chart can be standing alone as an image file; even be embedded within a text.

  • In RStudio, set the working directory with setwd(' ').
  • Set the option to print the output in a html file.
{r, message=FALSE}
library(googleVis)

op <- options(gvis.plot.tag='chart')
  • Set options back to original options.
options(op)
  • Generate the chart.
library(googleVis)

# Set the option to print here (alternative)
options(gvis.plot.tag='chart')

# Create the chart
M <- gvisMotionChart(Fruits,
                     idvar='Fruit',
                     timevar='Year',
                     options=list(width=400, height=350))

# Do not print the chart in the browser
#plot(M) # in the browser

# Print the chart as a html file
cat(M$html$chart, file = "M.html")
  • The file has several parts: JavaScript and HTML. The part that displays the chart is in the end.
<!-- divChart -->

<div id="MotionChartID2cd02805862d" 
     style="width: 400; height: 350;">
</div>
  • Following this bullet, in the Markdown document, paste the M.html code. First, open the HTML file to copy the code.
  • Modify the markup language with more styling parameters.
<div id="MotionChartID2cd02805862d" 
style="width: 400; height: 350; float:left;";>
</div>
  • The HTML snippet must follow the JavaScript snippet in the document. Move the HTML snippet within a text (the text can separate both snippets).
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
<div id="MotionChartID2cd02805862d" 
style="width: 400; height: 350; float:left;";>
</div>
Duis aute irure dolor...

Here is the result:

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Other static websites

There is a procedure for embedding graphics in:

  • WordPress.
  • Google Sites.
  • Blogger.
  • Google Code wiki pages.
  • Wikipedia.
  • others websites.

Dynamic websites

  • The R.rsp package allows the integration of R code into html code.
  • The rApache and brew packages support web application development using R and the Apache HTTP server.
  • Rook is a lightweight web server interface for R.
  • The shiny package builds interactive web application with R.

Charts

Consult the examples (further above); charts are similar to what we find in other packages.

gvisMotionChart is exclusive to googleVis.

gvisMotionChart

head(Fruits, 3)
# Output
   Fruit Year Location Sales Expenses Profit       Date
1 Apples 2008     West    98       78     20 2008-12-31
2 Apples 2009     West   111       79     32 2009-12-31
3 Apples 2010     West    89       76     13 2010-12-31
M <- gvisMotionChart(Fruits,
                     idvar='Fruit',
                     timevar='Year',
                     options=list(width=400, height=350))

# xvar =
# yvar =
# colorvar =
# sizevar =
# date.format =

plot(M)


Embedding with <iframe> or <embed>

After we generate the HTML chart or map, save the object as a HTML file.

library(htmlwidgets) 
library(DT) 

saveWidget(object, "googleVis.html")

Add these HTML snippets to the Markdown/HTML document.

<iframe seamless src="../img/googlevis.html" width=600px 
height=400px ></iframe>
<embed seamless src="../img/googlevis.html" width=600px height=400px ></embed>

In other words, we can either write the code or embed a file into the HTML/Markdown document.

Information from the object

M$type
M$chartid
"MotionChart"
"MotionChartID336e668836ab"

Maps

gvisGeoChart

head(Exports, 3)
# Output
        Country Profit Online
1       Germany      3   TRUE
2        Brazil      4  FALSE
3 United States      5   TRUE
Geo <- gvisGeoChart(Exports, 
                    locationvar = "Country",
                    colorvar = "Profit",
                    sizevar = "", # size of markers
                    hovervar = "", # text
                    options = list(projection="kavrayskiy-vii"))

# locationvar can be lat:long or address, country name, region, state, city

plot(Geo)
head(CityPopularity, 3)
# Output
      City Popularity
1 New York        200
2   Boston        300
3    Miami        400
Geo2 <- 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(Geo2)
CityPopularity3 <- data.frame(City = c('Montreal', 'Toronto'),
                              Popularity = c(400, 200))

Geo3 <- gvisGeoChart(CityPopularity3, 
                     locationvar='City',
                     colorvar='Popularity',
                     options=list(region = 'CA',
                                  height=350,
                                  displayMode='markers', 
                                  colorAxis="{values:[200,400,600,800], colors:[\'red', \'pink\', \'orange',\'green']}"))

plot(Geo3)
head(Andrew, 3)
# Output
        Date/Time UTC  Lat  Long Pressure_mb Speed_kt            Category
1 1992-08-16 18:00:00 10.8 -35.5        1010       25 Tropical Depression
2 1992-08-17 00:00:00 11.2 -37.4        1009       30 Tropical Depression
3 1992-08-17 06:00:00 11.7 -39.6        1008       30 Tropical Depression
     LatLong                                              Tip
1 10.8:-35.5 Tropical Depression<BR>Pressure=1010<BR>Speed=25
2 11.2:-37.4 Tropical Depression<BR>Pressure=1009<BR>Speed=30
3 11.7:-39.6 Tropical Depression<BR>Pressure=1008<BR>Speed=30
GeoMarker <- gvisGeoChart(Andrew,
                          locationvar="LatLong", 
                          sizevar='Speed_kt',
                          colorvar="Pressure_mb", 
                          options=list(region="US"))

plot(GeoMarker)


gvisMap or Google Maps

AndrewMap <- gvisMap(Andrew,
                     locationvar="LatLong" ,
                     tipvar="Tip", #  text displayed over the tip icon
                     options=list(showTip=TRUE, 
                                  showLine=TRUE, 
                                  enableScrollWheel=TRUE,
                                  mapType='terrain', 
                                  useMapTypeControl=TRUE))

plot(AndrewMap)

Editor

This is a fantastic option that let us start with one chart or map and change everything with a menu.

Editor <- gvisGeoChart(Exports, 
                       locationvar="Country",
                       colorvar="Profit",
                       options=list(gvis.editor='Edit me!'))

plot(Editor)


Tables with gvisTable

head(Stock, 3)
# Output
        Date  Device Value Title Annotation
1 2008-01-01 Pencils  3000  <NA>       <NA>
2 2008-01-02 Pencils 14045  <NA>       <NA>
3 2008-01-03 Pencils  5502  <NA>       <NA>
Table <- gvisTable(Stock, 
                   formats=list(Value="#,###"))

plot(Table)


head(Population, 3)
# Output
                                                                                 Rank       Country Population % of World Population
1    1         China 1339940000                0.1950
2    2         India 1188650000                0.1730
3    3 United States  310438000                0.0452
                                                                                                                                                                     Flag
1 <img src="http://upload.wikimedia.org/wikipedia/commons/thumb/f/fa/Flag_of_the_People%27s_Republic_of_China.svg/22px-Flag_of_the_People%27s_Republic_of_China.svg.png">
2                                                       <img src="http://upload.wikimedia.org/wikipedia/commons/thumb/4/41/Flag_of_India.svg/22px-Flag_of_India.svg.png">
3                               <img src="http://upload.wikimedia.org/wikipedia/commons/thumb/a/a4/Flag_of_the_United_States.svg/22px-Flag_of_the_United_States.svg.png">
  Mode       Date
1 TRUE 2010-10-09
2 TRUE 2010-10-09
3 TRUE 2010-10-09
PopTable <- gvisTable(Population, 
                      formats=list(Population="#,###",
                                   '% of World Population'='#.#%'),
                      options=list(page='enable'))

plot(PopTable)


Dashboards with gvisMerge

G <- gvisGeoChart(Exports,
                  locationvar="Country",
                  colorvar="Profit",
                  options=list(width=300, height=200))

T <- gvisTable(Exports,
               options=list(width=300, height=370))
GT <- gvisMerge(G, T, horizontal=FALSE)

plot(GT)


G <- gvisGeoChart(Exports,
                  locationvar="Country",
                  colorvar="Profit",
                  options=list(width=300, height=370))
GT <- gvisMerge(G, T, horizontal=TRUE)

plot(GT)

Options

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))


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)

R <- gvisColumnChart(df, 
                     options=list(vAxis='{baseline:0}',
                                  title="Combined Ratio %",
                                  legend="{position:'bottom'}"))

cat(R$html$chart, file = "GoogleVis/R.html") # save