October 21, 2015

googleVis

  • Provides an interface between Google Chart Tools and R
  • Includes the beauty of Hans Rosling's motion charts (purchase of Gapminder by Google)
  • https://github.com/mages/googleVis

install.packages('googleVis')

Who is Hans Rosling?

Hans Rosling?

9 Ted Talks (through 6/2014… the highest number - next was 6)

Introduction to Google Chart Tools

  • Google Chart Tools provide a way to visualize data on web sites
  • The API makes it easy to create interactive charts
  • Browser with internet connection required to display chart
  • Please read the Google Terms of Service before you start

Key ideas of googleVis

  • Transform R data frames into JSON objects with RJSONIO
library(RJSONIO)
dat <- data.frame(x=LETTERS[1:2], y=1:2)
cat(toJSON(dat)) 
## {
##  "x": [ "A", "B" ],
## "y": [ 1, 2 ] 
## }
  • Create wrapper functions in R which generate html files with references to Google's Chart Tools API
  • Display the HTML output with the R HTTP help server

The googleVis concept

  • Charts: 'gvis' + ChartType
  • For a motion chart we have
M <- gvisMotionChart(data, idvar='id', timevar='date', 
                     options=list(), chartid)
  • Output of googleVis is a list of list

  • Display the chart by simply plotting the output: plot(M)
  • Plot will generate a temporary html-file and open it in a new browser window
  • Specific parts can be extracted, e.g.
  • the chart: M$html$chart or
  • data: M$html$chart["jsData"]

Types of charts

  • Histogram, Line, Line with two axes, Bar, Column, Area, Stepped Area, Combo, Scatter, Bubble, Motion, Candlestick, Pie, Gauge, Table, Organization Chart, Tree Map, Sankey, Calendar, and Time line (to check on Annotation, Annotated time line)
  • Mapping: Intensity Map, Geo Chart, Geo markers, Google map markers,Geo Map

Run demo(googleVis) to see examples of all charts and read the vignette for more details.

Histogram

set.seed(123)
datHist=data.frame(A=rpois(100, 20),
                   B=rpois(100, 5),
                   C=rpois(100, 50))
suppressMessages(library(googleVis))
Hist <- gvisHistogram(datHist, options=list(
  legend="{ position: 'right', maxLines: 2 }",
  colors="['#5C3292', '#1A8763', '#871B47']",
  width=850, height=360))
plot(Hist)
#print(Hist,file="hist.html")

Line Chart

df=data.frame(country=c("US", "GB", "BR"), 
              val1=c(10,13,14), 
              val2=c(23,12,32))
Line <- gvisLineChart(df,options=list(width=750, height=500))
plot(Line)

Line with two axis

Line2 <- gvisLineChart(df, "country", c("val1","val2"),
                       options=list(
                         series="[{targetAxisIndex: 0},
                                 {targetAxisIndex:1}]",
                         vAxes="[{title:'val1'}, {title:'val2'}]",
                         width=750, height=400
                       ))
plot(Line2)

Customizing Lines

Dashed <-  gvisLineChart(df, xvar="country", yvar=c("val1","val2"),
                        options=list(
                          series="[{color:'green', targetAxisIndex: 0, 
                          lineWidth: 1, lineDashStyle: [2, 2, 20, 2, 20, 2]}, 
                          {color: 'blue',targetAxisIndex: 1, 
                          lineWidth: 2, lineDashStyle: [4, 1]}]",
                          vAxes="[{title:'val1'}, {title:'val2'}]", width=750,height=400
                        ))
plot(Dashed)

Bar Charts

Bar <- gvisBarChart(df,options=list(width=750, height=400))
plot(Bar)

Column Chart

Column <- gvisColumnChart(df,options=list(width=750, height=400))
plot(Column)

Area Chart

Area <- gvisAreaChart(df,options=list(width=750, height=400))
plot(Area)

Stepped Area Chart

SteppedArea <- gvisSteppedAreaChart(df, xvar="country", 
                                    yvar=c("val1", "val2"),
                                    options=list(isStacked=TRUE, width=750,height=400))
plot(SteppedArea)

Combo Chart

Combo <- gvisComboChart(df, xvar="country",
                        yvar=c("val1", "val2"),
                        options=list(seriesType="bars",
                                     series='{1: {type:"line"}}',width=750,height=400))
plot(Combo)

Scatter chart

head(women)
##   height weight
## 1     58    115
## 2     59    117
## 3     60    120
## 4     61    123
## 5     62    126
## 6     63    129

Scatter chart

Scatter <- gvisScatterChart(women, 
                            options=list(
                              legend="none",
                              pointSize=4,lineWidth=.5, 
                              title="Women", vAxis="{title:'weight (lbs)'}",
                              hAxis="{title:'height (in)'}", 
                              width=700, height=350))
plot(Scatter)

Customizing points

M <- matrix(nrow=6,ncol=6)
M[col(M)==row(M)] <- 1:6
dat <- data.frame(X=1:6, M)
SC <- gvisScatterChart(dat, 
                       options=list(
                         title="Customizing points",
                         legend="right",
                         pointSize=30,
                         series="{
                              0: { pointShape: 'circle' },
                              1: { pointShape: 'triangle' },
                              2: { pointShape: 'square' },
                              3: { pointShape: 'diamond' },
                              4: { pointShape: 'star' },
                              5: { pointShape: 'polygon' }
                              }",
                         width=750,height=400))

Customizing points

plot(SC)

More customizations

Line3 <-  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=750,
                          height=400                         
                        ))

More customizations

plot(Line3)

Bubble Chart

head(Fruits)
##     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
## 4 Oranges 2008     East    96       81     15 2008-12-31
## 5 Bananas 2008     East    85       76      9 2008-12-31
## 6 Oranges 2009     East    93       80     13 2009-12-31

Bubble Chart

Bubble <- gvisBubbleChart(Fruits, idvar="Fruit", 
                          xvar="Sales", yvar="Expenses",
                          colorvar="Year", sizevar="Profit",
                          options=list(
                            hAxis='{minValue:75, maxValue:125}',width=700,height=400))
plot(Bubble)

Motion chart example

M1=gvisMotionChart(Fruits, "Fruit", "Year", 
                     options=list(width=500, height=350))
#print(M1,file="M1.html")
plot(M1)

Candlestick chart

Candle <- gvisCandlestickChart(OpenClose, 
                               options=list(legend='none', width=700,height=400))
plot(Candle)

Pie charts (for those who insist on not changing) - Not you

Pie <- gvisPieChart(CityPopularity, options=list(width=700,height=400))
plot(Pie)

Gauge charts

Gauge <-  gvisGauge(CityPopularity, 
                    options=list(min=0, max=800, greenFrom=500,
                                 greenTo=800, yellowFrom=300, yellowTo=500,
                                 redFrom=0, redTo=300, width=400, height=300))
plot(Gauge)

Table

PopTable <- gvisTable(Population, 
                      formats=list(Population="#,###",
                                   '% of World Population'='#.#%'),
                      options=list(page='enable'))
plot(PopTable)

Organization Chart (double-click)

Org <- gvisOrgChart(Regions, 
                    options=list(width=600, height=250,
                                 size='large', allowCollapse=TRUE))
plot(Org)

Tree Map (left/right clicks)

Tree <- gvisTreeMap(Regions,  
                    "Region", "Parent", 
                    "Val", "Fac", 
                    options=list(fontSize=16))
plot(Tree)

Sankey chart

datSK <- data.frame(From=c(rep("A",3), rep("B", 3)),
                    To=c(rep(c("X", "Y", "Z"),2)),
                    Weight=c(5,7,6,2,9,4))

Sankey <- gvisSankey(datSK, from="From", to="To", weight="Weight",
                     options=list(
                       sankey="{link: {color: { fill: '#d799ae' } },
                            node: { color: { fill: '#a61d4c' },
                            label: { color: '#871b47' } }}"))

Sankey

plot(Sankey)

Calendar chart

Cal <- gvisCalendar(Cairo, 
                    datevar="Date", 
                    numvar="Temp",
                    options=list(
                      title="Daily temperature in Cairo",
                      height=320,
                      calendar="{yearLabel: { fontName: 'Times-Roman',
                               fontSize: 32, color: '#1A8763', bold: true},
                               cellSize: 10,
                               cellColor: { stroke: 'red', strokeOpacity: 0.2 },
                               focusedCellColor: {stroke:'red'}}")
)

Calendar chart

plot(Cal)

Timeline chart

datTL <- data.frame(Position=c(rep("President", 3), rep("Vice", 3)),
                    Name=c("Washington", "Adams", "Jefferson",
                           "Adams", "Jefferson", "Burr"),
                    start=as.Date(x=rep(c("1789-03-29", "1797-02-03", 
                                          "1801-02-03"),2)),
                    end=as.Date(x=rep(c("1797-02-03", "1801-02-03", 
                                        "1809-02-03"),2)))

Timeline <- gvisTimeline(data=datTL, 
                         rowlabel="Name",
                         barlabel="Position",
                         start="start", 
                         end="end",
                         options=list(timeline="{groupByRowLabel:false}",
                                      backgroundColor='#ffd', 
                                      height=350,
                                      colors="['#cbb69d', '#603913', '#c69c6e']"))
#print(Timeline,file="Timeline.html")

Timeline chart

plot(Timeline)

Intensity Map

Intensity <- gvisIntensityMap(df,options=list( width=750, height=400))
plot(Intensity)

Geo Chart

Geo=gvisGeoChart(Exports, locationvar="Country", 
                 colorvar="Profit",
                 options=list(projection="kavrayskiy-vii",
                 width=750, height=400))
plot(Geo)

Geo chart US

library(datasets)
states <- data.frame(state.name, state.x77)
GeoStates <- gvisGeoChart(states, "state.name", "Illiteracy",
                          options=list(region="US", displayMode="regions", resolution="provinces",
                                       width=600, height=400))
plot(GeoStates)

Geo markers: Hurricane Andrew track

GeoMarker <- gvisGeoChart(Andrew, "LatLong", 
                          sizevar='Speed_kt',
                          colorvar="Pressure_mb", 
                          options=list(region="US"))
plot(GeoMarker)

Google map: Hurricane Andrew Track

AndrewMap <- gvisMap(Andrew, "LatLong" , "Tip", 
                     options=list(showTip=TRUE, 
                                  showLine=TRUE, 
                                  enableScrollWheel=TRUE,
                                  mapType='terrain', 
                                  useMapTypeControl=TRUE))
plot(AndrewMap)

Geo Map: Hurricane Andrew Track

AndrewGeo <- gvisGeoMap(Andrew, 
                        locationvar="LatLong", 
                        numvar="Speed_kt", 
                        hovervar="Category", 
                        options=list(height=350, 
                                     region="US", 
                                     dataMode="markers"))
plot(AndrewGeo)

Merging

G <- gvisGeoChart(Exports, "Country", "Profit", 
                  options=list(width=600, height=400))
T <- gvisTable(Exports, 
               options=list(width=440, height=400))

GT <- gvisMerge(G,T, horizontal=TRUE) 
plot(GT)

Your turn to have fun!!