Reputation: 1
I’ve created a shiny app with raster layers plotted over a leaflet map. The user selects which raster to show with two drop down menus: one to select the type of data (mean or SD) the other to select a particular threshold (e.g., mean with 50-deg threshold, mean with 100-deg threshold). I’m having problems with the alignment of labels in the legend. The labels are right justified (see image), but I would like all the labels to be left justified.
Legend with incorrect formatting:
This answer that was just posted to a previous question works perfectly if I dont't have reactive rasters. However, when I try the same thing in code used to display reactive rasters nothing happens. Will this work if I'm using leafletProxy()
with clearControls()
? Here's the relevant bits of my code, including the shiny server object:
# Load file that lists summary statistics and thresholds
params <- read.csv("parameters.csv")
# Load RasterBrick and name layers
all_rast <- brick("mean-sd-brick.tif")
lyr_names <- paste0(tolower(params$summary), "_", params$threshold)
names(all_rast) <- lyr_names
# Modify function used to format legend labels to include dates when needed
myLabelFormat <- function(..., dates = FALSE){
if (dates) {
function(type = "numeric", cuts) {
dd <- parse_date_time(paste("2019", cuts), orders = "%Y %j")
dd <- format(dd, "%d %B")
paste0(cuts, " (", dd, ")")
}
} else {
labelFormat(...)
}
}
server <- shinyServer(function(input, output) {
reacRaster <- reactive({all_rast[[paste0(tolower(input$summary),
"_", input$threshold)]]})
legend_title <- reactive({ifelse(input$summary == "SD",
"SD (days)", "Day of year")})
legend_labels <- reactive({ifelse(input$summary == "SD",
myLabelFormat(dates = FALSE),
myLabelFormat(dates = TRUE))})
output$map <- renderLeaflet({
leaflet() %>%
fitBounds(lng1 = -88, lat1 = 35, lng2 = -65, lat2 = 47) %>%
addTiles()
})
observe({
pal <- colorNumeric(palette = "viridis",
domain = values(reacRaster()),
na.color = "transparent",
reverse = TRUE)
leafletProxy("map") %>%
clearImages() %>%
clearControls() %>%
addRasterImage(reacRaster(),
colors = pal,
group = "Value",
layerId = "Value",
opacity = input$opacity,
project = FALSE) %>%
addLegend("bottomright",
pal = pal,
values = values(reacRaster()),
labFormat = legend_labels(),
title = legend_title(),
opacity = 0.8) %>%
htmlwidgets::onRender("
function(el, x) {
var labels = el.querySelectorAll('.info.legend text'); // 1
labels.forEach(function(label) {
label.setAttribute('text-anchor', 'start'); // 2
label.setAttribute('dx', '5'); // set left indentation [px]
});
}
") %>%
addImageQuery(reacRaster(),
digits = 2,
type = "click",
position = "bottomleft",
prefix = "",
layerId = "Value",
project = TRUE)
}) # end observe
}) # end server
Upvotes: 0
Views: 41