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

app.R 12KB

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