There and Back Again competition entry https://shiny.petras.space/commute/
rstats
rshiny
census
competition
leaflet
javascript
stats-nz

app.R 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. library(shiny)
  2. library(shinyjs)
  3. library(leaflet)
  4. library(rgdal)
  5. library(dplyr)
  6. library(leaflet.extras)
  7. source("leafletfunctions.R")
  8. # work_travel <- read_csv("../travel-work.csv")
  9. load(file="datasets.RData")
  10. shpf <- readOGR(dsn="sa20025WGSfilcth")
  11. sa.in.dest <- shpf@data$SA22018_V1 %in% work_to$work_code
  12. sa.in.home <- shpf@data$SA22018_V1 %in% work_from$res_code
  13. transport.t <- c("Work at home", "Private car", "Company car",
  14. "Carpool", "Bus", "Train", "Bicycle", "Walk",
  15. "Ferry", "Other", "None")
  16. cols.labs <- c(transport.t[1:10], "Total")
  17. codelist <- shpf@data %>%
  18. mutate(sa2_code = as.numeric(as.character(SA22018_V1))) %>%
  19. select(sa2_code)
  20. startcols.res <- codelist %>% left_join(work_from, by = c("sa2_code" = "res_code"))
  21. startcols.res <- tencols[startcols.res$MAX]
  22. startcols.res <- ifelse(is.na(startcols.res), "#808080", startcols.res)
  23. startcols.work <- codelist %>% left_join(work_to, by = c("sa2_code" = "work_code"))
  24. startcols.work <- tencols[startcols.work$MAX]
  25. startcols.work <- ifelse(is.na(startcols.work), "#808080", startcols.work)
  26. hrstr <- "<hr style='border-top: 1px solid #000;'/>"
  27. # Define UI
  28. ui <- fluidPage(
  29. useShinyjs(),
  30. leafletjs,
  31. tags$style(type = "text/css",
  32. "html, body {
  33. width:100%;
  34. height:100%
  35. }
  36. #map {
  37. height: 100% !important;
  38. position: absolute !important;
  39. top: 0;
  40. left: 0;
  41. }
  42. #loading {
  43. cursor: progress !important;
  44. }
  45. #loading p {
  46. border-radius: 5px;
  47. background-color: rgba(255, 255, 255, 0.8);
  48. padding: 6px 8px;
  49. box-shadow: 0 0 15px rgba(0,0,0,0.2);
  50. font-size: 1.5em;
  51. font-weight: bold;
  52. }
  53. #mapcontrol {
  54. background-color: rgba(255, 255, 255, 0.8);
  55. border-radius: 5px;
  56. box-shadow: 0 0 15px rgba(0,0,0,0.2);
  57. padding: 6px 8px;
  58. font: 14px/16px Arial, Helvetica, sans-serif;
  59. }
  60. #lochtml ul {
  61. padding-left: 15px;
  62. }
  63. .radio label span p {
  64. margin-top: 3px;
  65. margin-bottom: 0px;
  66. }
  67. .leaflet-container {
  68. background-color: #84e1e1;
  69. }"),
  70. leafletOutput("map"),
  71. absolutePanel(top = 10, right = 10, id="mapcontrol",
  72. radioButtons("radioinout", label="Show commuters who",
  73. choiceNames = list(
  74. HTML("<p>Commute <b>from</b> selected area</p>"),
  75. HTML("<p>Commute <b>to</b> selected area</p>")),
  76. choiceValues = list(
  77. "res",
  78. "work"
  79. ),
  80. inline = FALSE),
  81. radioButtons("radiocolour",
  82. label = "Colour by",
  83. choiceNames = list(
  84. HTML("<p>Most common commute method</p>"),
  85. HTML("<p>Number of commuters</p>")
  86. ),
  87. choiceValues = list(
  88. "type",
  89. "number"
  90. ),
  91. inline = FALSE),
  92. div(id="locinfo",
  93. htmlOutput("lochtml"))),
  94. absolutePanel(bottom = 30, left = 10, id="loading",
  95. p("Loading..."))
  96. )
  97. # Define server logic
  98. server <- function(input, output) {
  99. sel.SA2.code <- reactiveVal(0)
  100. output$map <- renderLeaflet({
  101. leaf <- leaflet(shpf, options = leafletOptions(minZoom = 3, maxZoom = 13)) %>%
  102. addPolygons(color="#000", opacity = 1, weight=1,
  103. fillColor = startcols.res,
  104. layerId = ~SA22018_V1,
  105. label = shpf@data$SA22018__1,
  106. fillOpacity = 1) %>%
  107. setView(174, -41, 5) %>%
  108. addResetMapButton() %>%
  109. addLegend(position = "topleft",
  110. colors = c(tencols, "#808080"),
  111. labels = transport.t, opacity = 1,
  112. title = "Commute method")
  113. shinyjs::hideElement(selector="#loading p", asis = TRUE,
  114. anim=TRUE, animType = "slide", time=10)
  115. leaf
  116. })
  117. updateMap <- function() {
  118. shinyjs::showElement(selector="#loading p", asis = TRUE,
  119. anim=TRUE, animType = "slide")
  120. selcode <- sel.SA2.code()
  121. selcode <- ifelse(is.na(selcode), 0, selcode)
  122. psel <- selcode %in% shpf@data$SA22018_V1
  123. if (input$radiocolour == "type") {
  124. if (input$radioinout == "work") {
  125. fcols <- startcols.work
  126. if (psel) {
  127. codvs <- work_simp %>% filter(work_code == selcode)
  128. codvs <- codelist %>% left_join(codvs, by=c("sa2_code" = "res_code"))
  129. codvs <- tencols[codvs$MAX]
  130. fcols <- ifelse(is.na(codvs), "#808080", codvs)
  131. }
  132. } else {
  133. fcols <- startcols.res
  134. if (psel) {
  135. codvs <- work_simp %>% filter(res_code == selcode)
  136. codvs <- codelist %>% left_join(codvs, by=c("sa2_code" = "work_code"))
  137. codvs <- tencols[codvs$MAX]
  138. fcols <- ifelse(is.na(codvs), "#808080", codvs)
  139. }
  140. }
  141. lp <- leafletProxy("map", data = shpf) %>%
  142. setShapeStyle(layerId = ~SA22018_V1, fillColor = fcols) %>%
  143. clearControls() %>%
  144. addLegend(position = "topleft",
  145. colors = c(tencols, "#808080"),
  146. labels = transport.t, opacity = 1,
  147. title = "Commute method"
  148. ) %>%
  149. clearGroup("hpoly")
  150. } else {
  151. if (input$radioinout == "work") {
  152. if (psel) {
  153. codvs <- work_simp %>% filter(work_code == selcode)
  154. codvs <- codelist %>% left_join(codvs, by=c("sa2_code" = "res_code"))
  155. cvals <- ifelse(codvs$total == 0, NA, codvs$total)
  156. } else {
  157. codvs <- codelist %>%
  158. left_join(work_to, by = c("sa2_code" = "work_code"))
  159. cvals <- ifelse(codvs$total == 0, NA, codvs$total)
  160. }
  161. } else {
  162. if (psel) {
  163. codvs <- work_simp %>% filter(res_code == selcode)
  164. codvs <- codelist %>% left_join(codvs, by=c("sa2_code" = "work_code"))
  165. cvals <- ifelse(codvs$total == 0, NA, codvs$total)
  166. } else {
  167. codvs <- codelist %>%
  168. left_join(work_from, by = c("sa2_code" = "res_code"))
  169. cvals <- ifelse(codvs$total == 0, NA, codvs$total)
  170. }
  171. }
  172. cvr <- range(cvals, na.rm = TRUE)
  173. binner <- colorBin(c("white", "red"), cvr, bins = 7, pretty = TRUE)
  174. lp <- leafletProxy("map", data = shpf) %>%
  175. setShapeStyle(layerId = ~SA22018_V1, fillColor = binner(cvals)) %>%
  176. clearControls() %>%
  177. addLegend(position = "topleft",
  178. pal = binner,
  179. values = cvals, opacity = 1,
  180. na.label = "None",
  181. title = "Number of commuters") %>%
  182. clearGroup("hpoly")
  183. }
  184. if (psel) {
  185. lp %>% addPolygons(group = "hpoly",
  186. weight = 4,
  187. data = shpf[which(shpf@data$SA22018_V1 == selcode),],
  188. color = "#000000",
  189. fill = FALSE, opacity = 1)
  190. }
  191. shinyjs::hideElement(selector="#loading p", asis=TRUE,
  192. anim=TRUE, animType = "slide",
  193. time = 1)
  194. }
  195. observeEvent(input$map_click, ignoreInit = TRUE, {
  196. p <- input$map_click
  197. pdat <- data.frame(Longitude = p$lng,
  198. Latitude =p$lat)
  199. coordinates(pdat) <- ~ Longitude + Latitude
  200. proj4string(pdat) <- proj4string(shpf)
  201. ppoly <- over(pdat, shpf)
  202. codetmp <- as.numeric(as.character(ppoly[1,"SA22018_V1"]))
  203. codetmp <- ifelse(is.na(codetmp), 0, codetmp)
  204. sel.SA2.code(ifelse(sel.SA2.code() == codetmp, 0, codetmp))
  205. updateMap()
  206. })
  207. observeEvent(input$map_shape_mouseover, once=TRUE,{
  208. shinyjs::html(selector=".leaflet-control-attribution.leaflet-control",
  209. html = '
  210. <a href="http://leafletjs.com"
  211. title="A JS library for interactive maps">Leaflet</a> | <a
  212. href="https://datafinder.stats.govt.nz/data/category/census/2018/commuter-view/"
  213. title="Source data">
  214. StatsNZ</a> | <a href="https://petras.space/page/cv/" title="Hire me!">
  215. Petra Lamborn</a> | Numbers subject to <a
  216. href="http://archive.stats.govt.nz/about_us/legisln-policies-protocols/
  217. confidentiality-of-info-supplied-to-snz/safeguarding-confidentiality.aspx"
  218. title="A method of preserving confidentiality and anonymity">
  219. random rounding</a>
  220. '
  221. )
  222. })
  223. observeEvent(input$radioinout, ignoreInit = TRUE, {
  224. updateMap()
  225. })
  226. observeEvent(input$radiocolour, ignoreInit = TRUE, {
  227. updateMap()
  228. })
  229. output$lochtml <- renderUI({
  230. seled <- sel.SA2.code()
  231. seled <- ifelse(is.na(seled), 0, seled)
  232. if (!(seled %in% shpf@data$SA22018_V1)) {
  233. HTML(paste0(hrstr,
  234. "<p><em>No area selected</em></p>"))
  235. } else {
  236. namesel <- shpf@data$SA22018__1[shpf@data$SA22018_V1 == seled]
  237. if (input$radiocolour == "type") {
  238. str <- sprintf("<b>%s</b>", namesel)
  239. if (input$radioinout == "work") {
  240. str <- sprintf("<p>Commuting method of people who <b>work</b> in</p>
  241. <p><b><u>%s</u></b></p>", str)
  242. vals <- as.numeric(work_to[work_to$work_code == seled, 5:15])
  243. vals <- ifelse(is.na(vals), 0, vals)
  244. vals <- ifelse(vals < 0, "~0", as.character(vals))
  245. listi <- paste0(sprintf("<li>%s: %s</li>", cols.labs,
  246. vals),
  247. collapse="")
  248. str <- paste0(hrstr, str, "<ul>", listi, "</ul>")
  249. } else {
  250. str <- sprintf("<p>Commuting method of people who <b>live</b> in</p>
  251. <p><u>%s</u></p>", str)
  252. vals <- as.numeric(work_from[work_from$res_code == seled, 5:15])
  253. vals <- ifelse(is.na(vals), 0, vals)
  254. vals <- ifelse(vals < 0, "~0", as.character(vals))
  255. listi <- paste0(sprintf("<li>%s: %s</li>", cols.labs,
  256. vals),
  257. collapse="")
  258. str <- paste0(hrstr, str, "<ul>", listi, "</ul>")
  259. }
  260. HTML(str)
  261. } else {
  262. str <- hrstr
  263. if (input$radioinout == "work") {
  264. val <- as.numeric(work_to[work_to$work_code == seled, 15])
  265. val <- ifelse(is.na(val), 0, ifelse(val < 0, 0, val))
  266. str <- sprintf("%s<p>%d people commute <b>to</b></p>
  267. <p><b><u>%s</u></b></p>", str, val, namesel)
  268. if (val > 0) {
  269. subs <- work_simp %>% filter(work_code == seled) %>%
  270. arrange(desc(total)) %>% head(10)
  271. listi <- paste0(sprintf("<li>%s: %s</li>", subs$res_name,
  272. subs$total),
  273. collapse="")
  274. str <- sprintf("%s<p>Top areas to commute from<p>
  275. <ul>%s</ul>", str, listi)
  276. }
  277. } else {
  278. val <- as.numeric(work_from[work_from$res_code == seled, 15])
  279. val <- ifelse(is.na(val), 0, ifelse(val < 0, 0, val))
  280. str <- sprintf("%s<p>%d people commute <b>from</b></p>
  281. <p><b><u>%s</u></b></p>", str, val, namesel)
  282. if (val > 0) {
  283. subs <- work_simp %>% filter(res_code == seled) %>%
  284. arrange(desc(total)) %>% head(10)
  285. listi <- paste0(sprintf("<li>%s: %s</li>", subs$work_name,
  286. subs$total),
  287. collapse="")
  288. str <- sprintf("%s<p>Top areas to commute to<p>
  289. <ul>%s</ul>", str, listi)
  290. }
  291. }
  292. HTML(str)
  293. }
  294. }
  295. })
  296. }
  297. # Run the application
  298. shinyApp(ui = ui, server = server)