Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rebasing #2

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions demo-2/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# Demo-2
This is a demo of how a shiny app is structure, which uses a simple `TextInput` element to transfer information from the UI to R.
9 changes: 9 additions & 0 deletions demo-2/server.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
### Use input to create a string
shinyServer(function(input, output) {

# You can access the value of the widget with input$select, e.g.
output$userText <- renderText({
return(paste0('The user typed: ', input$text))
})

})
10 changes: 10 additions & 0 deletions demo-2/ui.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# Demo 2: Simple TextInput element
shinyUI(fluidPage(

# Create a text input element
textInput("text", label = h3("Text input"), value = "Enter text..."),

# Show output$userText
textOutput('userText')

))
2 changes: 2 additions & 0 deletions demo-3/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# Demo-3
This is a demo of how a shiny app is structure, which uses a simple `RadioInput` element to transfer information from the UI to R.
11 changes: 11 additions & 0 deletions demo-3/server.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
### Use input to create a string

### Use input to create a histogram
shinyServer(function(input, output) {

# Reder a histogram of a given color
output$histogram <- renderPlot({
x <- rnorm(1000)
return(hist(x, col = input$color))
})
})
9 changes: 9 additions & 0 deletions demo-3/ui.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# Demo 3: Simple RadioInput element
shinyUI(fluidPage(

# Radio buttons
radioButtons("color", label = "Color",
choices = list("Green" = 'green', "Blue" = 'blue'),
selected = 'green'),
plotOutput('histogram')
))
5 changes: 3 additions & 2 deletions exercise-1/exercise.R
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
# Exercise 1: Loading functions

# Set your directory
setwd('~/Documents/info-201/m14-shiny/exercise-1/')
setwd('~/Documents/INFO201/m14-shiny/exercise-1/')
df <- read.csv('https://raw.githubusercontent.com/plotly/datasets/master/2014_us_cities.csv')

# Load your buildMap.R Script

source('./scripts/buildMap.R')

# Use your BuildMap function to draw a map of the data
BuildMap(df)

24 changes: 22 additions & 2 deletions exercise-1/scripts/buildMap.R
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,30 @@ library(plotly)
# Try parameterize a few options, such as the title
# I suggest: https://plot.ly/r/bubble-maps/
BuildMap <- function(data) {
library(plotly)
df <- read.csv('https://raw.githubusercontent.com/plotly/datasets/master/2014_us_cities.csv')

df$q <- with(df, cut(pop, quantile(pop)))
levels(df$q) <- paste(c("1st", "2nd", "3rd", "4th", "5th"), "Quantile")
df$q <- as.ordered(df$q)

g <- list(
scope = 'usa',
projection = list(type = 'albers usa'),
showland = TRUE,
landcolor = toRGB("gray85"),
subunitwidth = 1,
countrywidth = 1,
subunitcolor = toRGB("white"),
countrycolor = toRGB("white")
)



p <- plot_geo(df, locationmode = 'USA-states', sizes = c(1, 250)) %>%
add_markers(
x = ~lon, y = ~lat, size = ~pop, color = ~q, hoverinfo = "text",
text = ~paste(df$name, "<br />", df$pop/1e6, " million")
) %>%
layout(title = '2014 US city populations<br>(Click legend to toggle)', geo = g)

return (p)
}
16 changes: 16 additions & 0 deletions exercise-3/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# Exercise-3
In this exercise, you'll practice building an interactive Plotly map in a Shiny application.

As in previous exercises, you should fork and clone this repository, then follow the instructions below.

## server.R
Your `server.R` file already loads the data you need, as well as scripts for building a map. Inside your `shinyServer`, you should do the following:

- Replace the static input `'population'` with a dynamic value that comes from your UI

## ui.R
Your `ui.R` file already has a `tabPanel` built displaying your map. In this section, you should add another `tabPanel` for your scatter-plot by doing the following:

- Add a `selectInput` (with a proper id) that allows you to select a variable to map (`population`, `votes`, or `ratio`)

Also, make sure you look at the `BuildMap` file and **understand how it is using variables to make a dynamic application**.
1 change: 1 addition & 0 deletions exercise-3/data/electoral_college.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
state,votes,populationAlabama,9,4858979Alaska,3,738432Arizona,11,6828065Arkansas,6,2978204California,55,39144818Colorado,9,5456574Connecticut,7,3590886Delaware,3,945934Florida,29,20271272Georgia,16,10214860Hawaii,4,1431603Idaho,4,1654930Illinois,20,12859995Indiana,11,6619680Iowa,6,3123899Kansas,6,2911641Kentucky,8,4425092Louisiana,8,4670724Maine,4,1329328Maryland,10,6006401Massachusetts,11,6794422Michigan,16,9922576Minnesota,10,5489594Mississippi,6,2992333Missouri,10,6083672Montana,3,1032949Nebraska,5,1896190Nevada,6,2890845New Hampshire,4,1330608New Jersey,14,8958013New Mexico,5,2085109New York,29,19795791North Carolina,15,10042802North Dakota,3,756927Ohio,18,11613423Oklahoma,7,3911338Oregon,7,4028977Pennsylvania,20,12802503Rhode Island,4,1056298South Carolina,9,4896146South Dakota,3,858469Tennessee,11,6600299Texas,38,27469114Utah,6,2995919Vermont,3,626042Virginia,13,8382993Washington,12,7170351 District of Columbia,3,672228West Virginia,5,1844128Wisconsin,10,5771337Wyoming,3,586107
Expand Down
1 change: 1 addition & 0 deletions exercise-3/data/state_codes.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
code,stateAL,AlabamaAK,AlaskaAZ,ArizonaAR,ArkansasCA,CaliforniaCO,ColoradoCT,ConnecticutDE,DelawareFL,FloridaGA,GeorgiaHI,HawaiiID,IdahoIL,IllinoisIN,IndianaIA,IowaKS,KansasKY,KentuckyLA,LouisianaME,MaineMD,MarylandMA,MassachusettsMI,MichiganMN,MinnesotaMS,MississippiMO,MissouriMT,MontanaNE,NebraskaNV,NevadaNH,New HampshireNJ,New JerseyNM,New MexicoNY,New YorkNC,North CarolinaND,North DakotaOH,OhioOK,OklahomaOR,OregonPA,PennsylvaniaRI,Rhode IslandSC,South CarolinaSD,South DakotaTN,TennesseeTX,TexasUT,UtahVT,VermontVA,VirginiaWA,WashingtonWV,West VirginiaWI,WisconsinWY,Wyoming
Expand Down
35 changes: 35 additions & 0 deletions exercise-3/scripts/buildMap.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# BuildMap file: function that returns a plotly map
library(plotly)
library(stringr)

# BuildMap function: fill this in with a function that returns a map:
# Derived from: https://plot.ly/r/choropleth-maps/

BuildMap <- function(data, map.var) {
# give state boundaries a white border
l <- list(color = toRGB("white"), width = 2)

# specify some map projection/options
g <- list(
scope = 'usa',
projection = list(type = 'albers usa'),
showlakes = TRUE,
lakecolor = toRGB('white')
)

# Make equation for map color / text
var.equation <- paste0('~', map.var)

# Plot
p <- plot_geo(data, locationmode = 'USA-states') %>%
add_trace(
z = eval(parse(text = var.equation)), text = ~state, locations = ~code,
color = eval(parse(text = var.equation)), colors = 'Purples'
) %>%
colorbar(title = "Color Title") %>%
layout(
title = str_to_title(map.var),
geo = g
)
return(p)
}
23 changes: 23 additions & 0 deletions exercise-3/server.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# server.R
library(dplyr)

# Read in data
setwd('~/Documents/info-201/m14-shiny/exercise-3/')
source('./scripts/buildMap.R')
df <- read.csv('./data/electoral_college.csv', stringsAsFactors = FALSE)
state.codes <- read.csv('./data/state_codes.csv', stringsAsFactors = FALSE)

# Join together state.codes and df
joined.data <- left_join(df, state.codes, by="state")

# Compute the electoral votes per 100K people in each state
joined.data <- joined.data %>% mutate(ratio = votes/population * 100000)

# Start shinyServer
shinyServer(function(input, output) {

# Render a plotly object that returns your map
output$map <- renderPlotly({
return(BuildMap(joined.data, 'population'))
})
})
9 changes: 9 additions & 0 deletions exercise-3/ui.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# ui.R
shinyUI(fluidPage(
mainPanel(
# Add a selectInput (with a proper id) that allows you to select a variable to map

# Use plotlyOutput to show your map
plotlyOutput('map')
)
))
24 changes: 24 additions & 0 deletions exercise-4/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Exercise-4
In this exercise, you'll practice building an a multi-tab Shiny application. The final product should look like this:

![scatter plot in shiny app](imgs/scatter.png)

The Map panel is already built for you to model. Your scatter panel should enable users to search for a state in the scatterplot.

As in previous exercises, you should fork and clone this repository, then follow the instructions below.

## server.R
Your `server.R` file already loads the data you need, as well as scripts for building a map and a scatter plot. Inside your `shinyServer`, you should do the following:

- Create a `scatter` property on your `output` object. That property should be a `renderPlotly` object that returns a scatterplot (`BuildScatter`)
- Make sure to pass your data and search string (i.e., `input$search`) to your `BuildScatter` function.

## ui.R
Your `ui.R` file already has a `tabPanel` built displaying your map. In this section, you should add another `tabPanel` for your scatter-plot by doing the following:

- Create a `tabPanel` to show your scatter plot
- Add a `titlePanel` to your tab
- Create a `sidebarLayout` for this tab (page)
- Create a `sidebarPanel` for your controls
- In your `sidebarPanel`, make a `textInput` widget for searching for a state in your scatter plot
- Create a `mainPanel`, in which you should display your plotly Scatter plot
1 change: 1 addition & 0 deletions exercise-4/data/electoral_college.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
state,votes,populationAlabama,9,4858979Alaska,3,738432Arizona,11,6828065Arkansas,6,2978204California,55,39144818Colorado,9,5456574Connecticut,7,3590886Delaware,3,945934Florida,29,20271272Georgia,16,10214860Hawaii,4,1431603Idaho,4,1654930Illinois,20,12859995Indiana,11,6619680Iowa,6,3123899Kansas,6,2911641Kentucky,8,4425092Louisiana,8,4670724Maine,4,1329328Maryland,10,6006401Massachusetts,11,6794422Michigan,16,9922576Minnesota,10,5489594Mississippi,6,2992333Missouri,10,6083672Montana,3,1032949Nebraska,5,1896190Nevada,6,2890845New Hampshire,4,1330608New Jersey,14,8958013New Mexico,5,2085109New York,29,19795791North Carolina,15,10042802North Dakota,3,756927Ohio,18,11613423Oklahoma,7,3911338Oregon,7,4028977Pennsylvania,20,12802503Rhode Island,4,1056298South Carolina,9,4896146South Dakota,3,858469Tennessee,11,6600299Texas,38,27469114Utah,6,2995919Vermont,3,626042Virginia,13,8382993Washington,12,7170351 District of Columbia,3,672228West Virginia,5,1844128Wisconsin,10,5771337Wyoming,3,586107
Expand Down
1 change: 1 addition & 0 deletions exercise-4/data/state_codes.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
code,stateAL,AlabamaAK,AlaskaAZ,ArizonaAR,ArkansasCA,CaliforniaCO,ColoradoCT,ConnecticutDE,DelawareFL,FloridaGA,GeorgiaHI,HawaiiID,IdahoIL,IllinoisIN,IndianaIA,IowaKS,KansasKY,KentuckyLA,LouisianaME,MaineMD,MarylandMA,MassachusettsMI,MichiganMN,MinnesotaMS,MississippiMO,MissouriMT,MontanaNE,NebraskaNV,NevadaNH,New HampshireNJ,New JerseyNM,New MexicoNY,New YorkNC,North CarolinaND,North DakotaOH,OhioOK,OklahomaOR,OregonPA,PennsylvaniaRI,Rhode IslandSC,South CarolinaSD,South DakotaTN,TennesseeTX,TexasUT,UtahVT,VermontVA,VirginiaWA,WashingtonWV,West VirginiaWI,WisconsinWY,Wyoming
Expand Down
Binary file added exercise-4/imgs/scatter.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
35 changes: 35 additions & 0 deletions exercise-4/scripts/buildMap.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# BuildMap file: function that returns a plotly map
library(plotly)
library(stringr)

# BuildMap function: fill this in with a function that returns a map:
# Derived from: https://plot.ly/r/choropleth-maps/

BuildMap <- function(data, map.var) {
# give state boundaries a white border
l <- list(color = toRGB("white"), width = 2)

# specify some map projection/options
g <- list(
scope = 'usa',
projection = list(type = 'albers usa'),
showlakes = TRUE,
lakecolor = toRGB('white')
)

# Make equation for map color / text
var.equation <- paste0('~', map.var)

# Plot
p <- plot_geo(data, locationmode = 'USA-states') %>%
add_trace(
z = eval(parse(text = var.equation)), text = ~state, locations = ~code,
color = eval(parse(text = var.equation)), colors = 'Purples'
) %>%
colorbar(title = "Color Title") %>%
layout(
title = str_to_title(map.var),
geo = g
)
return(p)
}
27 changes: 27 additions & 0 deletions exercise-4/scripts/buildScatter.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# BuildMap file: function that returns a plotly map
library(plotly)
library(stringr)
### Build Scatter ###
BuildScatter <- function(data, search = '', xvar = 'population', yvar = 'votes') {
# Filter down to state, then graph

# Get x and y max
xmax <- max(data[,xvar]) * 1.5
ymax <- max(data[,yvar]) * 1.5
x.equation <- paste0('~', xvar)
y.equation <- paste0('~', yvar)
data <- data %>%
filter(grepl(search, state))

plot_ly(data=data, x = eval(parse(text = x.equation)),
y = eval(parse(text = y.equation)),
mode='markers',
marker = list(
opacity = .4,
size = 10
)) %>%
layout(xaxis = list(range = c(0, xmax), title = xvar),
yaxis = list(range = c(0, ymax), title = yvar)
) %>%
return()
}
32 changes: 32 additions & 0 deletions exercise-4/server.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# server.R
library(dplyr)
library(plotly)
library(shiny)

# Read in data
# setwd('~/Documents/info-201/m14-shiny/exercise-4/')
source('./scripts/buildMap.R')
source('./scripts/buildScatter.R')
df <- read.csv('./data/electoral_college.csv', stringsAsFactors = FALSE)
state.codes <- read.csv('./data/state_codes.csv', stringsAsFactors = FALSE)

# Join together state.codes and df
joined.data <- left_join(df, state.codes, by="state")

# Compute the electoral votes per 100K people in each state
joined.data <- joined.data %>% mutate(ratio = votes/population * 100000)

# Start shinyServer
shinyServer(function(input, output) {

# Render a plotly object that returns your map
output$map <- renderPlotly({
return(BuildMap(joined.data, input$mapvar))
})

# Create a `scatter` property on your `output` object. That property shoudl be a `renderPlotly` object that returns a scatterplot (`BuildScatter`)
output$scatter <- renderPlotly({
return(BuildScatter(joined.data, input$text))
})

})
48 changes: 48 additions & 0 deletions exercise-4/ui.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
# ui.R
library(shiny)
library(plotly)
shinyUI(navbarPage('Electoral College',
# Create a tab panel for your map
tabPanel('Map',
titlePanel('Electoral College Votes'),
# Create sidebar layout
sidebarLayout(

# Side panel for controls
sidebarPanel(

# Input to select variable to map
selectInput('mapvar', label = 'Variable to Map', choices = list("Population" = 'population', 'Electoral Votes' = 'votes', 'Votes / Population' = 'ratio'))
),

# Main panel: display plotly map
mainPanel(
plotlyOutput('map')
)
)
),

# Create a tabPanel to show your scatter plot
tabPanel('Scatter',
# Add a titlePanel to your tab
titlePanel("Electoral College Votes"),

# Create a sidebar layout for this tab (page)
sidebarLayout(

# Create a sidebarPanel for your controls
sidebarPanel(

# Make a textInput widget for searching for a state in your scatter plot
textInput('text', label = "State to Map", value = "")

),

# Create a main panel, in which you should display your plotly Scatter plot
mainPanel(
plotlyOutput('scatter')
)

)
)
))