Skip to content

Commit

Permalink
proxy gradient
Browse files Browse the repository at this point in the history
  • Loading branch information
pvictor committed Jun 12, 2018
1 parent ce2aa44 commit 8b3bf4e
Show file tree
Hide file tree
Showing 5 changed files with 270 additions and 21 deletions.
1 change: 1 addition & 0 deletions NAMESPACE
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ export(d3_map)
export(d3_map_proxy)
export(r2d3map)
export(update_continuous_breaks)
export(update_continuous_gradient)
export(use_r2d3map)
importFrom(classInt,classIntervals)
importFrom(geojsonio,geo2topo)
Expand Down
43 changes: 22 additions & 21 deletions R/d3_map_proxy.R
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,6 @@ d3_map_proxy <- function(shinyId, data = NULL, session = shiny::getDefaultReacti
#'
#' @export
#'
#' @importFrom classInt classIntervals
#'
#' @examples
#' \dontrun{
Expand Down Expand Up @@ -104,6 +103,21 @@ update_continuous_breaks <- function(proxy, var, palette = NULL, direction = 1,



#' Update a gradient scale in Shiny
#'
#' @param proxy A \code{d3_map_proxy} object.
#' @param var New var to use on the map.
#' @param low,high Colours for low and high ends of the gradient.
#' @param range A length two vector to force range of data.
#'
#' @export
#'
#' @examples
#' \dontrun{
#'
#' # todo
#'
#' }
update_continuous_gradient <- function(proxy, var, low = NULL, high = NULL, range = NULL) {
if (!"d3_map_proxy" %in% class(proxy))
stop("This function must be used with a d3_map_proxy object", call. = FALSE)
Expand All @@ -115,30 +129,17 @@ update_continuous_gradient <- function(proxy, var, low = NULL, high = NULL, rang
warning("Invalid variable!", call. = FALSE)
return(invisible(proxy))
}
if (!is.null(range))
var_ <- c(var_, range)
var_ <- sort(unique(var_))
var_scale <- rescale(var_, to = c(0, 1))
if (!is.null(low) & !is.null(high)) {
pal <- seq_gradient_pal(low = low, high = high)
colors <- pal(var_scale)
colors_legend <- pal(seq(from = 0, to = 1, along.with = var_scale))
} else {
colors <- NULL
colors_legend <- NULL
}
.r2d3maps_proxy(
proxy = proxy,
name = "continuous-gradient",
color_var = var,
range_var = var_,
scale_var = var_scale,
colors = if (!is.null(colors)) c(colors, "#fafafa") else NULL,
colors_legend = colors_legend,
legend_label = append(
x = range(var_, na.rm = TRUE),
values = diff(range(var_, na.rm = TRUE))/2,
after = 1
scale = scale_gradient(
data = data,
vars = var,
low = low,
mid = NULL,
high = high,
range = range
)
)
}
Expand Down
133 changes: 133 additions & 0 deletions dev/example-proxy-gradient.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@



# Packages ----------------------------------------------------------------

library(shiny)
library(shinyWidgets)
library( r2d3maps )
library( r2d3 )
library( rnaturalearth )
library( magrittr )
library( dplyr )


# data --------------------------------------------------------------------

# shapes
africa <- ne_countries(continent = "Africa", returnclass = "sf")


# drinking water data
data("water_africa")
glimpse(water_africa)


# add data to shapes

africa <- left_join(
x = africa %>% select(adm0_a3_is, name, geometry),
y = water_africa %>% filter(year == 2015),
by = c("adm0_a3_is" = "iso3")
)
africa$national_at_least_basic <- round(africa$national_at_least_basic)
africa$national_limited_more_than_30_mins <- round(africa$national_limited_more_than_30_mins)
africa$national_unimproved <- round(africa$national_unimproved)
africa$national_surface_water <- round(africa$national_surface_water)

# d3_map(shape = africa) %>%
# add_continuous_gradient(var = "national_at_least_basic", range = "auto") %>%
# add_legend(title = "Population with at least basic access", suffix = "%")





# app ---------------------------------------------------------------------


get_brewer_name <- function(name) {
pals <- RColorBrewer::brewer.pal.info[rownames(RColorBrewer::brewer.pal.info) %in% name, ]
res <- lapply(
X = seq_len(nrow(pals)),
FUN = function(i) {
RColorBrewer::brewer.pal(n = pals$maxcolors[i], name = rownames(pals)[i])
}
)
unlist(res)
}
colors_choices <- get_brewer_name(c("Blues", "Greens", "Reds", "Oranges", "Purples"))


ui <- fluidPage(
tags$h2("Example proxy with gradient scale"),
fluidRow(
column(
width = 4,
radioButtons(
inputId = "var",
label = "Indicator:",
choices = list(
"Basic" = "national_at_least_basic",
"Limited" = "national_limited_more_than_30_mins",
"Unimproved" = "national_unimproved",
"Surface water" = "national_surface_water"
),
inline = TRUE
),
pickerInput(
inputId = "col_lowest", label = "Lowest color",
choices = colors_choices, selected = "#9ECAE1",
options = list(`size` = 9, `show-tick` = TRUE),
choicesOpt = list(
style = "margin-left:-10px;",
content = sprintf(
"<div style='width:100%%;padding:5px;border-radius:4px;background:%s;color:%s'>%s</div>",
colors_choices,
ifelse(seq_along(colors_choices) %% 9 %in% c(6, 7, 8, 0), "white", "black"),
colors_choices
)
)
),
pickerInput(
inputId = "col_highest", label = "Highest color",
choices = colors_choices, selected = "#08306B",
options = list(`size` = 9, `show-tick` = TRUE),
choicesOpt = list(
style = "margin-left:-10px;",
content = sprintf(
"<div style='width:100%%;padding:5px;border-radius:4px;background:%s;color:%s'>%s</div>",
colors_choices,
ifelse(seq_along(colors_choices) %% 9 %in% c(6, 7, 8, 0), "white", "black"),
colors_choices
)
)
)
),
column(
width = 7,
d3Output(outputId = "mymap", width = "600px", height = "500px")
)
)
)

server <- function(input, output, session) {

output$mymap <- renderD3({
d3_map(shape = africa) %>%
add_continuous_gradient(var = "national_at_least_basic", range = "auto") %>%
add_legend(title = "Population with at least basic access", suffix = "%")
})

observeEvent(list(input$var, input$col_lowest, input$col_highest), {
d3_map_proxy(shinyId = "mymap", data = africa) %>%
update_continuous_gradient(var = input$var, low = input$col_lowest, high = input$col_highest, range = "auto")
}, ignoreInit = TRUE)

}

shinyApp(ui, server)




86 changes: 86 additions & 0 deletions inst/js/r2d3maps2.js
Original file line number Diff line number Diff line change
Expand Up @@ -343,6 +343,7 @@ r2d3.onRender(function(json, div, width, height, options) {
.text(options.legend_opts.title);

linearGradientSvg.append("text")
.attr("class", "tick-label")
.attr("x", 10)
.attr("y", height-5)
.style("font-size", 11)
Expand All @@ -355,6 +356,7 @@ r2d3.onRender(function(json, div, width, height, options) {
}
});
linearGradientSvg.append("text")
.attr("class", "tick-label")
.attr("x", widthLegend/2+5)
.attr("y", height-5)
.style("font-size", 11)
Expand All @@ -367,6 +369,7 @@ r2d3.onRender(function(json, div, width, height, options) {
}
});
linearGradientSvg.append("text")
.attr("class", "tick-label")
.attr("x", widthLegend)
.attr("y", height-5)
.style("font-size", 11)
Expand Down Expand Up @@ -395,6 +398,89 @@ r2d3.onRender(function(json, div, width, height, options) {
.attr("stroke", options.stroke_col)
.attr("stroke-width", options.stroke_width + "px")
.attr("d", path);

if (HTMLWidgets.shinyMode) {
if (typeof id != 'undefined') {
Shiny.addCustomMessageHandler('update-r2d3maps-continuous-gradient-' + id,
function(proxy) {
key_gdt1 = proxy.data.color_var;
colors_gdt1 = proxy.data.scale[key_gdt1].colors;
colors_leg_gdt1 = proxy.data.scale[key_gdt1].colors_legend;
leg_lab_gdt1 = proxy.data.scale[key_gdt1].legend_label;
scale_var_gdt1 = proxy.data.scale[key_gdt1].scale_var;
range_var_gdt1 = proxy.data.scale[key_gdt1].range_var;

colorGradient.domain(scale_var_gdt1);
colorInterpolateGradient.domain(d3.extent(range_var_gdt1));
colorGradient.range(colors_gdt1);

if (options.legend) {
linearGradient.selectAll("stop").remove();
//Append multiple color stops by using D3's data/enter step
linearGradient.selectAll("stop")
.data( colors_leg_gdt1 )
.enter().append("stop")
.attr("offset", function(d,i) { return i/(colors_leg_gdt1.length-1); })
.attr("stop-color", function(d) { return d; });

linearGradientSvg.selectAll("text.tick-label").remove();
linearGradientSvg.append("text")
.attr("class", "tick-label")
.attr("x", 10)
.attr("y", height-5)
.style("font-size", 11)
.style("text-anchor", "middle")
.text(function() {
if (options.legend_opts.d3_format) {
return d3.format(options.legend_opts.d3_format)(leg_lab_gdt1[0]);
} else {
return options.legend_opts.prefix + leg_lab_gdt1[0] + options.legend_opts.suffix;
}
});
linearGradientSvg.append("text")
.attr("class", "tick-label")
.attr("x", widthLegend/2+5)
.attr("y", height-5)
.style("font-size", 11)
.style("text-anchor", "middle")
.text(function() {
if (options.legend_opts.d3_format) {
return d3.format(options.legend_opts.d3_format)(leg_lab_gdt1[1]);
} else {
return options.legend_opts.prefix + leg_lab_gdt1[1] + options.legend_opts.suffix;
}
});
linearGradientSvg.append("text")
.attr("class", "tick-label")
.attr("x", widthLegend)
.attr("y", height-5)
.style("font-size", 11)
.style("text-anchor", "middle")
.text(function() {
if (options.legend_opts.d3_format) {
return d3.format(options.legend_opts.d3_format)(leg_lab_gdt1[2]);
} else {
return options.legend_opts.prefix + leg_lab_gdt1[2] + options.legend_opts.suffix;
}
});
}

map.transition()
.duration(750)
//.ease("linear")
//.attr("fill", "#fafafa")
.attr("fill", function(d) {
if (d.properties[key_gdt1] == 'NA') {
return options.colors.na_color;
} else {
return colorGradient(colorInterpolateGradient(d.properties[key_gdt1]));
}
})
.attr("d", path);
}
);
}
}
}

} else {
Expand Down
28 changes: 28 additions & 0 deletions man/update_continuous_gradient.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 8b3bf4e

Please sign in to comment.