This repository has been archived by the owner on Nov 19, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
sentiment_neighbourhoods_module.R
248 lines (229 loc) · 7.89 KB
/
sentiment_neighbourhoods_module.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
mapPlotUI <- function(id, selected){
ns <- NS(id)
if (selected == "Sentiment") {
tagList(
description = div(
"This map shows the search results that mention each neighbourhood. The colors correspond to the average sentiment expressed in each of those documents."
),
plot = div(
div(
style = "max-width: 1200px;",
shiny::uiOutput(ns("map_plot_output_ui")) %>%
shinycssloaders::withSpinner()
),
div(
align="center",
style = "max-width: 1200px;",
sentiment_legend()
)
),
exclude = div(
div(
style = "max-width: 1200px;",
uiOutput(ns("neighbourhoods_exclude_ui")),
)
)
)
} else if (selected == "Count") {
tagList(
description = div(
"This map shows the number of documents in the search results that mention each neighbourhood."
),
plot = div(
div(
style = "max-width: 1200px;",
shiny::uiOutput(ns("map_plot_output_ui")) %>%
shinycssloaders::withSpinner()
)
),
exclude = div(
div(
style = "max-width: 1200px;",
uiOutput(ns("neighbourhoods_exclude_ui")),
)
)
)
}
}
mapPlot <- function(input, output, session,
query_info, selected) {
neighbourhoods = sf::st_read(get_configs()$neighbourhoods_file, quiet = TRUE)
output$neighbourhoods_exclude_ui <- renderUI({
shinyWidgets::dropdownButton(
'Some neighbourhoods can overshadow results for other neighbourhoods. You can exclude neighbourhoods from this analysis by entering them in the box below.',
br(),
selectizeInput(session$ns("neighbourhoods_exclude"),
label = "Exclude Neighbourhoods:",
choices = sort(neighbourhoods$descriptive_name),
selected = c(),
multiple = TRUE,
options = list(placeholder = 'Type here')),
circle = FALSE,
status = "primary",
icon = icon("cog"),
width = "300px",
tooltip = shinyWidgets::tooltipOptions(title = "Map Options")
)
})
plot_alt_map = reactive({
req(query_info()$num_hits > 0)
colour_map = get_sentiment_colourmap()
aggregations = query_text_depot(query_info = query_info(),
aggregates_json = sentimentNeighbourhoodsQuery())
aggregations = parse_aggregates(es_results = aggregations)
bbox = sf::st_bbox(neighbourhoods)
min.lat = as.numeric(bbox$ymin)
max.lat = as.numeric(bbox$ymax)
min.lng = as.numeric(bbox$xmin)
max.lng = as.numeric(bbox$xmax)
map = leaflet() %>%
addProviderTiles(providers$Stadia.StamenTonerLite, options = providerTileOptions(noWrap = TRUE)) %>%
fitBounds(min.lng, min.lat, max.lng, max.lat)
if (nrow(aggregations$hoods.names.buckets) > 0) {
hood_stats = aggregations$hoods.names.buckets %>%
group_by(key) %>%
summarize(
doc_count = sum(doc_count),
avg_sentiment = mean(neighbourhood_to_sentiment.avg_sentiment.value),
.groups = "drop"
) %>%
rename(name = key) %>%
mutate(label1 = paste0(name, "<br/>", "Doc Count: ", doc_count, "<br/>",
"Sentiment: ", round(avg_sentiment, 2))) %>%
mutate(label2 = paste0(name, "<br/>", "Doc Count: ", doc_count))
hoods_df = neighbourhoods %>%
left_join(hood_stats, by = c("descriptive_name" = "name"))
na_ind = which(is.na(hoods_df$avg_sentiment))
hoods_df$doc_count[na_ind] = 0
hoods_df$label1[na_ind] = paste0(hoods_df$name[na_ind], ": ", NA)
hoods_df$label2[na_ind] = paste0(hoods_df$name[na_ind], ": ", NA)
if (length(input$neighbourhoods_exclude) > 0) {
hoods_df = dplyr::filter(hoods_df, !(descriptive_name %in% input$neighbourhoods_exclude))
}
pal = colorNumeric(palette = "Blues", domain = hoods_df$doc_count, reverse = FALSE)
hoods_df$label = ifelse(!is.na(hoods_df$avg_sentiment),
as.character(cut(hoods_df$avg_sentiment,
breaks = c(colour_map$lower, Inf),
labels = colour_map$label,
include.lowest = TRUE,
right = TRUE)),
NA)
# Remove repeats of "NEUTRAL" so join doesnt cause issues:
colours = colour_map %>%
select(colour, legend_text_colour, label) %>%
distinct()
hoods_df = dplyr::left_join(hoods_df, colours, by = c("label" = "label"))
if (selected == "Sentiment") {
map = map %>%
addPolygons(
data = hoods_df,
# fillColor = ~pal(sentiment_mean),
fillColor = ~colour,
weight = 2,
opacity = 1,
color = "white",
dashArray = "3",
fillOpacity = 0.7,
highlight = highlightOptions(
weight = 3,
color = "#666666",
dashArray = "",
fillOpacity = 0.7,
bringToFront = TRUE
),
label = ~lapply(label1, htmltools::HTML),
labelOptions = labelOptions(
style = list("font-weight" = "normal", padding = "3px 8px"),
textsize = "15px",
direction = "auto"
)
)
} else if (selected == "Count") {
map = map %>%
addPolygons(
data = hoods_df,
fillColor = ~pal(doc_count),
weight = 2,
opacity = 1,
color = "white",
dashArray = "3",
fillOpacity = 0.7,
highlight = highlightOptions(
weight = 3,
color = "#666666",
dashArray = "",
fillOpacity = 0.7,
bringToFront = TRUE
),
label = ~lapply(label2, htmltools::HTML),
labelOptions = labelOptions(
style = list("font-weight" = "normal", padding = "3px 8px"),
textsize = "15px",
direction = "auto"
)
)
}
} else { # No neighbourhood data to plot, so just show an info message:
map = map %>%
addControl("<span style='font-weight: bold; color: red'>No Neighbourhoods were mentioned in your search results!</span>", position = "topleft", className = "info legend")
}
map
})
output$map_plot_output <- leaflet::renderLeaflet({
plot_alt_map()
})
output$map_plot_output_ui <- renderUI({
leaflet::leafletOutput(session$ns("map_plot_output"), height = 500)
})
output$sentiment_colour_scale <- renderPlot({
colour_map = get_sentiment_colourmap()
sentimentLegendPlot(colour_mapping = colour_map)
})
}
sentimentNeighbourhoodsQuery <- function() {
'
"aggs": {
"group_by_index": {
"terms": {
"field": "_index"
},
"aggs" : {
"hoods": {
"nested": {
"path": "neighbourhoods"
},
"aggs": {
"names": {
"terms": {
"size": 500,
"field": "neighbourhoods.name.keyword"
},
"aggs": {
"count_sum": {
"sum": {
"field": "neighbourhoods.count"
}
},
"ratio_sum": {
"sum": {
"field": "neighbourhoods.ratio"
}
},
"neighbourhood_to_sentiment": {
"reverse_nested": {},
"aggs": {
"avg_sentiment": {
"avg": {
"field": "sentiment_polarity"
}
}
}
}
}
}
}
}
}
}
}'
}