School’s out: Building Interactive R Apps with shiny, googleVis in our R Academy

October 24, 2013
By

(This article was first published on eoda, R und Datenanalyse » eoda english R news, and kindly contributed to R-bloggers)

In our R Academy course “Interactive Datavisualization with R” participants learned today how to build interactive graphics in R using the shiny and the googleVis package.

Interactive Web Application with R

Interactive Web Application with R

Rstudios shiny package is a great way to build an Application for interactive visualizations out of R.
For our example App we recreated Hans Rosslings (Gapminder) Visualization which puts a countries Life-Expectancy in relation with its Gross-Domestic-Product.

We used the data from datamarket.com via the rdatamarket Package. We combined data from Gapminder(Population), the World Bank (GDP) and from the United Nations (Life-Expectancy) with each other. Datamarket.com even offers an R-console snippet for importing the data directly into R (Under Export).

The following lines of code shows what you need to do. Have fun with  R in the web.

# TODO: Add comment
# 
# Author: msc
###############################################################################

library("rdatamarket")
library("shiny")


#getting Data from datamarket.com
#life_expectancy and gdp
dminit("ba22bf5bdf044aaf980cdbde3504248c")
life_expectancy <- dmlist("15r2!hrp")
gdp <- dmlist("15c9!hd1")

#population
dminit("ba22bf5bdf044aaf980cdbde3504248c")
population <- dmlist("1cfl!r3d")


#renaming the value variable
names(gdp)[3] <- "GDP"
names(life_expectancy)[3] <- "life_expectancy"
names(population)[3] <- "Population"

#merge to one dataframe
data <- merge(gdp,life_expectancy, by = c("Country","Year"))
data <- merge(data, population, by = c("Country","Year"))

#data is only until 2008 complete
data <- data[data$Year <= 2008,]

#reducing data for only a few countries
data$Country <- as.character(data$Country)

selection <- c("Afghanistan","Australia","Austria","Belgium","Bolivia",
		"Brazil","Cambodia","Azerbaijan", "Chile","China","Denmark","Estonia","Ethiopia","Finland","France",
		"Georgia","Germany","Ghana","Greece","India","Indonesia","Iraq","Italy",
		"Japan","Lithuania","Luxembourg","Mexico","New Zealand", "Niger", "Norway", "Poland", "Portugal",
		"Rwanda", "Somalia", "South Africa", "Spain", "Sweden", "Switzerland", "Turkey",
		"Uganda", "Ukraine", "United Kingdom", "United States", "Vietnam")

data <- subset(data, Country %in% selection)

#saving the data
save(data, file = "shiny_beispiel/data.RData")

#run shiny app localy
runApp("shiny_beispiel")



# TODO: Add comment
# 
# Author: msc
###############################################################################


if(!"googleVis"%in%installed.packages())install.packages("googleVis", repos = "http://ftp5.gwdg.de/pub/misc/cran/")
library("googleVis")

shinyServer(function(input, output) {
			
			load("data.RData")
			
			data$Population <- data$Population/1000
									
			output$main_plot <- renderGvis({
						
						if(input$xAchse == "log. GDB"){
							data$GDP <- log(data$GDP)
						}else{
							data$GDP <- data$GDP
						}
						
						if(input$all == TRUE){
							country_filter <- input$country_filter1
						}
						if(input$all == FALSE){
							country_filter <- input$country_filter2
						}
						
												
						#it seems that gvisMotionChart needs different variables for idvar and colorvar
						data$CountryCol <- data$Country
												
						gvisMotionChart(data[data$Country %in% country_filter,],
								idvar = "Country",
								timevar = "Year",
								xvar = "GDP",
								yvar = "life_expectancy",
								colorvar = "CountryCol",
								sizevar = "Population",
								options = list(showChartButtons = FALSE,
										       showSidePanel = FALSE,
											   showXScalePicker = FALSE,
											   showYScalePicker = FALSE)
								)
						
						
					})
			
			output$map <- renderGvis({
						
						if(input$all == TRUE){
							country_filter <- input$country_filter1
						}
						if(input$all == FALSE){
							country_filter <- input$country_filter2
						}
						
						year_filter <- input$year_filter
						
						data$hover <- paste0("Life-Expectancy ",data$Country,": ",round(data$life_expectancy))
						
						gvisGeoChart(data[data$Country %in% country_filter & data$Year == year_filter,], locationvar = "Country", colorvar = "GDP", hovervar = "hover")
					})
			
			
		})







 


# TODO: Add comment
# 
# Author: msc
###############################################################################

library("shiny")

if(!"googleVis"%in%installed.packages())install.packages("googleVis", repos = "http://ftp5.gwdg.de/pub/misc/cran/")
library("googleVis")

load('data.RData')

#Buiding a HTML Table

shinyUI(pageWithSidebar(
				headerPanel(tags$body(tags$img(src="eoda_logo.png", width = "400px", align ="right"),
								       h1("Life-Expectancy ~ GDP per capita"),
									   h2("(random Country preselection)"),
									   h5("sometimes changes doen't take effect immediatly in this case please refresh the whole page"))),
					   
				sidebarPanel(
						selectInput('xAchse', 'X Axis', c('GDP', 'log. GDB')),
						checkboxInput(inputId = 'all',label = 'all countries', value = TRUE),
						conditionalPanel(condition = 'input.all == true',
								checkboxGroupInput(inputId = 'country_filter1',
										label = 'Countries', unique(data$Country),
										selected = unique(data$Country))),
						conditionalPanel(condition = 'input.all == false',
								checkboxGroupInput('country_filter2',
										label = 'Countries', choices = unique(data$Country)))
				),
				mainPanel(h3("MotionChart"),
						  h4("(circle-size = population in tsd)"),
						  htmlOutput(outputId = "main_plot"),
						  h3("World Map"),
						  h4("(colour range = GDP per capita/ additional Life-Expectancy per MouseOver Effect)"),
						  htmlOutput(outputId = "map"),
						  sliderInput(inputId = "year_filter",
								      label = "Year",
									  min = 1960,
									  max = 2008,
						              value = 2008,
									  format = "####")
						 )
		))


In our R Academy we help you to become an expert in R – check it out!

To leave a comment for the author, please follow the link and comment on his blog: eoda, R und Datenanalyse » eoda english R news.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...



If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.