This is an R Markdown document created with examples of how to work with rCharts. Based on Coursera’s Data Products course.
The basic function for a specific type of rChart is Nplot, which calls a specific Javascript plotting library. If you input the following commands
require(rCharts)
haireye = as.data.frame(HairEyeColor)
n1=nPlot(Freq ~ Hair, group = 'Eye', type = 'multiBarChart', data = subset(haireye, Sex == 'Male'))
n1$save('figs/chart1.html', cdn=TRUE)
it will save an html file (chart1.hmtl), containing the interactive plot, in the folder figs (if it exists):
You can view the html code generated by typing n1$html or you can view the chart by opening the URL you saved:
browseURL("figs/chart1.html")
names(iris) = gsub("\\.", "", names(iris)) # remove the dots from the variable names in iris
n2=rPlot(SepalLength ~ SepalWidth | Species, data = iris, color = 'Species', type = 'point')
n2$save('figs/chart2.html', cdn=TRUE)
n2
will display an interactive plot where you can hover over each of the dots:
hair_eye = as.data.frame(HairEyeColor)
n3=rPlot(Freq ~ Hair | Eye, color = 'Eye', data = hair_eye, type = 'bar')
n3$save('figs/chart3.html', cdn=TRUE)
will display an interactive plot where you can hover over each bar:
Another one:
data(economics, package = "ggplot2")
econ <- transform(economics, date = as.character(date))
m1 <- mPlot(x = "date", y = c("psavert", "uempmed"), type = "Line", data = econ)
m1$set(pointSize = 0, lineWidth = 1)
m1$save('figs/chart4.html', cdn=TRUE)
will display an interactive plot where you can hover over each line:
And yet another:
require(reshape2)
uspexp <- melt(USPersonalExpenditure)
names(uspexp)[1:2] = c("category", "year")
x1 <- xPlot(value ~ year, group = "category", data = uspexp, type = "line-dotted")
x1$save('figs/chart5.html', cdn=TRUE)
will display:
The next one is too cool…
map3 <- Leaflet$new()
map3$setView(c(51.505, -0.09), zoom = 13) # find the coordinates you'd like to input at http://www.openstreetmap.org/
map3$marker(c(51.5, -0.09), bindPopup = "<p> Hi. I am a popup </p>")
map3$marker(c(51.495, -0.083), bindPopup = "<p> Hi. I am another popup </p>")
map3$save('figs/chart6.html', cdn=TRUE)
will display:
Let’s costumise it:
map3 <- Leaflet$new()
map3$setView(c(40.21863, -8.41602), zoom = 13) # find the coordinates you'd like to input at http://www.openstreetmap.org/
map3$marker(c(40.21897, -8.41628), bindPopup = "<p> Faculdade de Medicina. </p>")
map3$save('figs/chart7.html', cdn=TRUE)
so that it will display:
I know we all want to see some more…
usp = reshape2::melt(USPersonalExpenditure)
# get the decades into a date Rickshaw likes
usp$Var2 <- as.numeric(as.POSIXct(paste0(usp$Var2, "-01-01")))
p4 <- Rickshaw$new()
p4$layer(value ~ Var2, group = "Var1", data = usp, type = "area", width = 560)
# add a helpful slider this easily; other features TRUE as a default
p4$set(slider = TRUE)
p4$save('figs/chart8.html', cdn=TRUE)
will display:
And finally
h1 <- hPlot(x = "Wr.Hnd", y = "NW.Hnd", data = MASS::survey, type = c("line",
"bubble", "scatter"), group = "Clap", size = "Age")
h1$save('figs/chart9.html', cdn=TRUE)
will display:
n3$publish('Myplot', host="rpubs")
n2$publish('Myplot', host="gist")
Types of charts:
gvisMotionChartgvisGeoChartgvisTablegvisLineChartgvisColumnChartgvisTreeMapsuppressPackageStartupMessages(library(googleVis))
M <- gvisMotionChart(Fruits, "Fruit", "Year",
options=list(width=600, height=400))
print(M, file="figs/gvis1.html")
plot(M)
will generate (sometimes if I do plot(M) or open the html document it will not display anything. It usually works again if i restart Rstudio. Go figure…)
op <- options(gvis.plot.tag='chart')
CityPopularity$Mean=mean(CityPopularity$Popularity)
CC <- gvisComboChart(CityPopularity, xvar='City',
yvar=c('Mean', 'Popularity'),
options=list(seriesType='bars',
width=450, height=300,
title='City Popularity',
series='{0: {type:\"line\"}}'))
print(CC, file="figs/gvis2.html")
It will generate
Please note that the Motion Chart is only displayed when hosted on a web server, or is placed in a directory which has been added to the trusted sources in the security settings of Macromedia.
Something else that’s really cool:
G= gvisGeoChart(Exports, locationvar="Country",
colorvar="Profit",options=list(width=600, height=400))
print(G, file="figs/gvis3.html")
It will generate
Let’s focus on Europe:
G= gvisGeoChart(Exports, locationvar="Country",
colorvar="Profit",options=list(width=600, height=400,region="150"))
print(G, file="figs/gvis4.html")
It will generate
Or maybe just Portugal:
PTcities=data.frame(cityname=c("Lisbon", "Porto", "Coimbra"), Size=c(600, 250, 150), LatLong=c("38.71:-9.14", "41.15:-8.61", "40.22:-8.43"))
G= gvisGeoChart(PTcities, locationvar="LatLong",
colorvar="Size",options=list(width=600, height=400,region="PT", resolution="provinces"))
print(G, file="figs/gvis5.html")
It will generate
An alternative
PT=data.frame(cityname=c("Lisboa", "Porto", "Coimbra"), Size=c(600, 250, 150))
G= gvisGeoChart(PT, locationvar="cityname",
colorvar="Size",options=list(width=600, height=400,region="PT", resolution="provinces"))
print(G, file="figs/gvis6.html")
will generate
Note: to find info on country codes, region names, etc, go to https://developers.google.com/chart/interactive/docs/gallery/geochart#Regions.
Another example:
df=data.frame(label=c("US", "GB", "BR"), val1=c(1,3,4), val2=c(23,12,32))
Line =gvisLineChart(df, xvar="label", yvar=c("val1","val2"),
options=list(title="Hello World", legend="bottom",
titleTextStyle="{color:'red', fontSize:18}",
vAxis="{gridlines:{color:'red', count:3}}",
hAxis="{title:'My Label', titleTextStyle:{color:'blue'}}",
series="[{color:'green', targetAxisIndex: 0},
{color: 'blue',targetAxisIndex:1}]",
vAxes="[{title:'Value 1 (%)', format:'##,######%'},
{title:'Value 2 (\U00A3)'}]",
curveType="function", width=500, height=300
))
print(Line, file="figs/gvis7.html")
will generate
G <- gvisGeoChart(Exports, "Country", "Profit",options=list(width=200, height=100))
T1 <- gvisTable(Exports,options=list(width=200, height=270))
M <- gvisMotionChart(Fruits, "Fruit", "Year", options=list(width=400, height=370))
GT <- gvisMerge(G,T1, horizontal=FALSE)
GTM <- gvisMerge(GT, M, horizontal=TRUE,tableOptions="bgcolor=\"#CCCCCC\" cellspacing=10")
print(GTM, file="figs/gvis8.html")
will generate
setwd(“C:/Users/Miguel/Desktop/data_science/data_products”)