Skip to content

Commit 18c936c

Browse files
committed
Merge pull request #4 from blmoore/auto-legends
merge legends branch
2 parents 511c363 + 8898c88 commit 18c936c

File tree

4 files changed

+138
-32
lines changed

4 files changed

+138
-32
lines changed

debug.R

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
library("leaflet")
2+
3+
4+
ax <- readRDS("data/accidents.rds")
5+
6+
input <- list()
7+
input$color <- "none"
8+
title <- input$color
9+
10+
col <- switch(input$color,
11+
"Severity" = list(var="severity", type="factor"),
12+
"Casualties" = list(var="no_casualt", type="int"),
13+
"Time" = list(var="a_time_hr", type="int"),
14+
"Vehicles" = list(var="no_vehicle", type="int"),
15+
"Speed limit" = list(var="speed_limi", type="int"),
16+
list(var="none", type="none"))
17+
message(col)
18+
19+
col_fn <- function(col){
20+
if(col$type != "none"){
21+
if(col$type == "int") {
22+
return(colorNumeric("Set1", domain=ax[[col$var]]))
23+
} else {
24+
return(colorFactor("Set1", domain=ax[[col$var]]))
25+
}} else return( function(...) "black" )
26+
}
27+
28+
map <- leaflet(ax) %>% addTiles()
29+
30+
pal <- colorNumeric("Set1", ax$speed_limi)
31+
32+
if(col[[1]] == "none"){
33+
map %>%
34+
addCircleMarkers(data=ax, ~long, ~lat, radius=8, fillOpacity=.3,
35+
color=NA, fillColor = ~col_fn(col)(ax[[col$var]]))
36+
} else {
37+
map %>%
38+
addCircleMarkers(data=ax, ~long, ~lat, radius=8, fillOpacity=.3,
39+
color=NA, fillColor = ~col_fn(col)(ax[[col$var]])) %>%
40+
addLegend("bottomleft", pal=col_fn(col), values=ax[[col$var]], title=title,
41+
layerId="legend")
42+
}

server.R

Lines changed: 89 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -11,15 +11,17 @@ accidents <- readRDS("data/accidents.rds")
1111
accidents <- accidents[sample(1:nrow(accidents), 2000),]
1212

1313
accident_desc <- function(row)
14-
with(as.list(row), paste0(strong(
15-
format.Date(a_date, "%a %d %B %Y"), ": "), "A ",
14+
with(as.list(row), paste0("<b>",
15+
format.Date(a_date, "%a %d %B %Y"), ":</b> A ",
1616
tolower(severity), " collision in a ", speed_limi,
1717
" MPH zone, involving ", no_vehicle, " vechicle(s) with ",
1818
no_casualt, " casualtie(s). Weather was ", tolower(weather)))
1919

2020
strs <- apply(accidents, 1, accident_desc)
2121
names(strs) <- NULL
2222

23+
accidents$text <- strs
24+
2325
# summary plot munging
2426
d2 <- accidents %>% group_by(as.factor(ym)) %>%
2527
summarise(n=n())
@@ -38,37 +40,99 @@ colnames(clean) <- c("Severity", "No. vehicles",
3840
"Road conditions", "Special conditions", "Postcode")
3941

4042
shinyServer(function(input, output, session) {
41-
43+
44+
getData <- reactive({
45+
subset(accidents, a_date >= input$dates[[1]] & a_date <= input$dates[[2]])
46+
})
47+
48+
getAlpha <- reactive({
49+
#message("alpha changed : ", input$alpha)
50+
input$alpha
51+
})
52+
53+
legend <- reactive({
54+
proxy <- leafletProxy("mymap", session, data=accidents)
55+
if(input$color == "Speed limit"){
56+
message("triggered")
57+
pal <- colorFactor(palette="Set1", domain=factor(accidents$speed_limi))
58+
l <- proxy %>%
59+
addLegend("bottomleft", pal=pal, values=~speed_limi,
60+
labFormat=labelFormat(suffix=" mph"), title="Speed limit")
61+
return(l)
62+
} else {
63+
return(proxy)
64+
}
65+
})
66+
4267
output$mymap <- renderLeaflet({
43-
accidents <- subset(accidents, a_date >= input$dates[[1]] & a_date <= input$dates[[2]])
68+
# build base map on load
69+
ax <- getData()
70+
71+
l <- leaflet(data=ax) %>%
72+
addTiles(urlTemplate="http://openmapsurfer.uni-hd.de/tiles/roadsg/x={x}&y={y}&z={z}") %>%
73+
addTiles('http://{s}.tile.openstreetmap.se/hydda/roads_and_labels/{z}/{x}/{y}.png',
74+
attribution='&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>') %>%
75+
setView(lng=-3.19, lat=55.95, zoom=13) #%>%
4476

45-
fillv <- if(input$color == "None") "black" else
46-
if(input$color == "Severity") pal[as.factor(accidents$severity)] else
47-
if(input$color == "Casualties") pal[as.factor(accidents$no_casualt)] else
48-
if(input$color == "Time") cont_pal[accidents$a_time_hr] else
49-
if(input$color == "Vehicles") pal[as.factor(accidents$no_vehicle)] else
50-
pal[as.factor(accidents$speed_limi)]
77+
# stop spinner
78+
session$sendCustomMessage(type = "map_done", "done")
5179

52-
l <- leaflet(data=accidents) %>%
53-
addTiles(urlTemplate="http://openmapsurfer.uni-hd.de/tiles/roadsg/x={x}&y={y}&z={z}") %>%
54-
addTiles('http://{s}.tile.openstreetmap.se/hydda/roads_and_labels/{z}/{x}/{y}.png',
55-
attribution='&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>') %>%
56-
setView(lng=-3.19, lat=55.95, zoom=13) %>%
57-
addCircleMarkers(~long, ~lat, radius=~(no_vehicle+.8)**1.5, fillOpacity=input$alpha,
58-
color=NA, popup=strs, weight=2, fillColor = fillv)
59-
60-
session$sendCustomMessage(type = "map_done", "done")
80+
l
81+
})
82+
83+
observe({
84+
# modify map of changed input i.e. colour by
85+
ax <- getData()
86+
title <- input$color
87+
88+
col <- switch(input$color,
89+
"Severity" = list(var="severity", type="factor"),
90+
"Casualties" = list(var="no_casualt", type="int"),
91+
"Time" = list(var="a_time_hr", type="int"),
92+
"Vehicles" = list(var="no_vehicle", type="int"),
93+
"Speed limit" = list(var="speed_limi", type="int"),
94+
list(var="none", type="none"))
95+
96+
col_fn <- function(col){
97+
if(col$type != "none"){
98+
if(col$type == "int") {
99+
return(colorNumeric("Set1", domain=ax[[col$var]]))
100+
} else {
101+
return(colorFactor("Set1", domain=ax[[col$var]]))
102+
}} else return( function(...) "black" )
103+
}
104+
105+
if(col$var == "none"){
106+
l <- leafletProxy("mymap", session, data=ax) %>%
107+
addCircleMarkers(~long, ~lat, radius=~1+(no_vehicle**1.5), fillOpacity=getAlpha(),
108+
color=NA, popup=~text, fillColor = "black",
109+
layerId=paste0("p", 1:nrow(ax))) %>%
110+
removeControl(layerId="legend")
111+
112+
} else {
61113

62-
l
114+
l <- leafletProxy("mymap", session, data=ax) %>%
115+
addCircleMarkers(~long, ~lat, radius=~1+(no_vehicle**1.5), fillOpacity=getAlpha(),
116+
color=NA, popup=~text, fillColor = ~col_fn(col)(ax[[col$var]]),
117+
layerId=paste0("p", 1:nrow(ax))) %>%
118+
addLegend("bottomleft", pal=col_fn(col), values=ax[[col$var]],
119+
title=title, layerId="legend")
120+
}
121+
122+
l
63123
})
64124

65125
output$monthTotals <- renderPlot({
66-
ggplot(d2, aes(x=zoo::as.Date(zoo::as.yearmon(ym)), y=n)) +
67-
geom_area() + theme_minimal() +
68-
labs(x="", y="Recorded collisions\nper month") +
69-
scale_y_continuous(expand=c(0,0))
126+
d2 <- getData() %>% group_by(as.factor(ym)) %>%
127+
summarise(n=n())
128+
colnames(d2) <- c("ym", "n")
129+
130+
print(ggplot(d2, aes(x=zoo::as.Date(zoo::as.yearmon(ym)), y=n)) +
131+
geom_area() + theme_minimal() +
132+
labs(x="", y="Recorded collisions\nper month") +
133+
scale_y_continuous(expand=c(0,0)))
70134
})
71-
135+
72136
output$table <- DT::renderDataTable({
73137
DT::datatable(clean, filter = 'top', options = list(
74138
pageLength = 10, autoWidth = TRUE))

styles.css

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,13 +27,13 @@ h1, h2, h3, h4 { font-weight: 400; }
2727
padding: 0 20px 20px 20px;
2828
cursor: move;
2929
/* Fade out while not hovering */
30-
opacity: 0.65;
30+
opacity: 0.7;
3131
zoom: 0.9;
3232
transition: opacity 500ms 1s;
3333
}
3434
#controls:hover {
3535
/* Fade in while hovering */
36-
opacity: 0.95;
36+
opacity: 1;
3737
transition-delay: 0;
3838
}
3939

ui.R

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -39,11 +39,11 @@ $( 'div#mymap' ).append(spinner.el);"),
3939
label = 'Occurred between:',
4040
start = as.Date("2010-01-01"), end = as.Date("2013-07-01")),
4141

42-
selectInput("color", "Color by:",
42+
selectInput("color", "Colour by:",
4343
choices=c("None", "Severity", "Casualties", "Time", "Vehicles", "Speed limit")),
4444

4545
sliderInput("alpha", "Opacity:",
46-
min=0, max=1, value=.3),
46+
min=0, max=1, value=.4, step=.025, ticks=T),
4747

4848
hr(),
4949
h4("Summary plots"),
@@ -65,10 +65,10 @@ $( 'div#mymap' ).append(spinner.el);"),
6565
$( "div#mymap" ).remove(spinner);
6666
});')
6767

68-
),
68+
)#,
6969

70-
tags$div(id="cite",
71-
a("@benjaminlmoore", href="http://twitter.com/benjaminlmoore"))
70+
# tags$div(id="cite",
71+
# a("@benjaminlmoore", href="http://twitter.com/benjaminlmoore"))
7272
)
7373
), tabPanel("Table", DT::dataTableOutput("table"))
7474
)

0 commit comments

Comments
 (0)