-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.R
280 lines (231 loc) · 9.6 KB
/
app.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
#------------------------------------------------------------------------------
# FLIGHT EXPLORER
#------------------------------------------------------------------------------
# GRUPO 9:
# Carlos Rodriguez
# Francisco del Val
# Jose Lopez
# Octavio del Sueldo
# Iñigo Martiarena
#------------------------------------------------------------------------------
# LIBRERIAS
# Shiny
library(shiny)
library(shinyWidgets)
library(shinydashboard)
# Base de datos
library(nycflights13)
library(tidyverse)
# Plots
library(ggplot2)
library(maps)
library(geosphere)
library(ggmap)
library(cowplot)
#------------------------------------------------------------------------------
# DATASET
# Cargamos los datasets de vuelos y los visualizamos
data("flights")
head(flights)
data("airports")
head(airports)
# Realizamos un join con los datasets que queremos, cuya clave de union sera el
# destino con faa
data_raw <- flights %>%
inner_join(airports, c("dest" = "faa"))
# Realizamos un join con los datasets que queremos, cuya clave de union sera el
# origen con faa
# De esta manera, tendremos tanto las coordenadas de destino como de origen
data_raw <- data_raw %>%
inner_join(airports, c("origin" = "faa"))
# Seleccionamos aquellas columnas que nos interesan
data_raw <- select(.data = data_raw, c(sched_dep_time, dep_delay, arr_delay,
origin, dest, distance,
name.x, lat.x, lon.x,
name.y, lat.y, lon.y))
# Cambiamos los nombres de las variables a minusculas y sustituimos los
# .x por dest
data_raw <- rename_with(data_raw, ~ tolower(gsub(".x", "_dest",
.x, fixed = TRUE)))
# Cambiamos los nombres de las variables a minusculas y sustituimos los
# .y por origin
data_raw <- rename_with(data_raw, ~ tolower(gsub(".y", "_origin",
.x, fixed = TRUE)))
# Eliminamos los NaN
data <- drop_na(data_raw)
# Hacemos un attach para trabajar mas comodamente
attach(data)
# Una vez tenemos el dataset limpio ya podemos comenzar a trabajar con shiny
#------------------------------------------------------------------------------
# UI
ui <- dashboardPage(
dashboardHeader(
title = "Flight Explorer"
),
dashboardSidebar(
# Seleccionamos los aeropuertos de origen
pickerInput(inputId = "origin",
label = "Origin",
choices = sort(unique(name_origin), decreasing = F),
options = list("actions-box" = TRUE),
multiple = TRUE,
selected = "John F Kennedy Intl"
),
# Seleccionamos los aeropuertos de destino
pickerInput(inputId = "dest",
label = "Destination",
choices = sort(unique(name_dest), decreasing = F),
options = list("actions-box" = TRUE),
multiple = TRUE,
selected = "Los Angeles Intl"
),
# Seleccionamos la variable agregada
selectInput(inputId = "variable",
label = "Size by",
choices = list("Arrival delay" = "arr_delay",
"Departure delay" = "dep_delay",
"Distance" = "distance"),
multiple = FALSE,
selected = "distance"
)
),
dashboardBody(
# Plot del mapa
plotOutput("map",
brush = "selection"),
# Plot de los histogtamas en box para que salga mas estetico
fluidRow(
box(title = "Arrival delay in minutes",
status = "primary",
plotOutput("hist_arr_delay")
),
box(title = "Departure delay in minutes",
status = "primary",
plotOutput("hist_dep_delay")
),
box(title = "Distance flown in milles",
status = "primary",
plotOutput("hist_dist")),
box(title = "Scheduled departure time",
status = "primary",
plotOutput("hist_depart_time"))
)
)
)
#------------------------------------------------------------------------------
# SERVER
server <- function(input, output) {
#----------------------------------------------------------------------------
# HISTOGRAMAS
# Definimos el filtro con el que haremos los plots
data_filter <- reactive({
# Si no has seleccionado variables el validate muestra un error
validate(
need(input$dest != "", "Please select destination"),
need(input$origin != "", "Please select origin")
)
# Generamos el dataset de la seleccion (brushed)
data_brushed <- brushedPoints(data,
input$selection,
xvar = "lon_dest",
yvar = "lat_dest")
# Creamos una condición, si el usuario ha hecho una selección en el mapa,
# utilizas ese dataset, sino utiliza las varibales indicadasd en el ui
if (nrow(data_brushed) > 0) {
return(data_brushed)
} else {
return(filter(.data = data,
name_origin == input$origin,
name_dest == input$dest))
}
})
# Ploteamos los histogramas
# Histograma arr_delay
output$hist_arr_delay <- renderPlot({
# Si no hay información de los histogramas, utilizamos validate()
validate(
need(nrow(data_filter()) > 0, "No flights in this corridor!")
)
ggplot(data = data_filter(), aes(x = arr_delay)) +
geom_histogram(col = "cadetblue4", fill = "cadetblue3") +
xlab("Minutes")
})
# Histograma dep_delay
output$hist_dep_delay <- renderPlot({
# Si no hay información de los histogramas, utilizamos validate()
validate(
need(nrow(data_filter()) > 0, "No flights in this corridor!")
)
ggplot(data = data_filter(), aes(x = dep_delay)) +
geom_histogram(col = "cadetblue4", fill = "cadetblue3") +
xlab("Minutes")
})
# Histograma distance
output$hist_dist <- renderPlot({
# Si no hay información de los histogramas, utilizamos validate()
validate(
need(nrow(data_filter()) > 0, "No flights in this corridor!"),
need(length(unique(data_filter()$distance)) != 1,
paste0(unique(data_filter()$distance)))
)
ggplot(data = data_filter(), aes(x = distance)) +
geom_histogram(col = "cadetblue4", fill = "cadetblue3") +
xlab("Milles")
})
# Histograma dep_hour
output$hist_depart_time <- renderPlot({
# Si no hay información de los histogramas, utilizamos validate()
validate(
need(nrow(data_filter()) > 0, "No flights in this corridor!")
)
ggplot(data = data_filter(), aes(x = sched_dep_time)) +
geom_histogram(col = "cadetblue4", fill = "cadetblue3") +
xlab("Minutes")
})
#----------------------------------------------------------------------------
# MAPA
output$map <- renderPlot({
usa <- map_data("usa")
states <- map_data("state")
# Mapa de USA
mapa <- ggplot() +
geom_polygon(data = usa,
aes(x = long, y = lat, group = group),
fill = NA,
color = "black") +
coord_fixed(1.3)
# Mapa de los Estados
mapa <- mapa +
geom_polygon(data = states,
aes(x = long, y = lat, group = group),
color = "gray35", fill = "lemonchiffon1") +
guides(fill = FALSE)
# Mapa con los aeropuertos
# Si quisieramos ver la media de las variables agregadas (Size by)
# deberíamos utilizar este dataset, el problema es que no puedes hacer
# la media de un string, por lo que no funciona. En el ggplot, se debería
# cambiar input$variable por data_size$avg.
data_size <- data_filter() %>%
group_by(name_dest, lon_dest, lat_dest) %>%
summarise(avg = mean(input$variable))
# Ploteamos
mapa <- mapa +
geom_point(data = data_filter(),
aes_string(x = "lon_dest", y = "lat_dest", size = input$variable),
color = "tomato1", fill = "tomato1", shape = 1)
mapa <- mapa +
geom_point(data = data_filter(),
aes(x = lon_origin, y = lat_origin),
color = "green", fill = "green", shape = 19, size = 3)
mapa <- mapa +
geom_segment(data = data_filter(),
aes(x = lon_origin, y = lat_origin,
xend = lon_dest, yend = lat_dest),
linetype = 2, lwd = 0.75)
mapa +
theme(panel.background = element_rect(fill = "lightblue",
colour = "lightblue"))
})
}
# Run the application
shinyApp(ui = ui, server = server)