0

I'm using a defined color palette in my circle markers to show the category of each point on the map. The points that show up on the map are colored according to the palette but the palette does not correspond to the levels I used in the domain. They seem to be colored randomly.

The relevant bit is the colorfactor definition and the leaflet plot:

library(dplyr)
library(tidyverse)
library(leaflet)
library(sf)
library(shiny)
library(leafpop)


acc<-read.csv('acc.csv')
names(acc) <- tolower(names(acc))

pal <- colorFactor(c("red", "navy", "green"), domain = c("1. Fatal", "2. Serious", "3. Slight"))

acc <- acc %>%
  st_as_sf(coords = c("easting", "northing"), crs = 27700) %>% st_transform('+proj=longlat +datum=WGS84') %>%
  
  dplyr::mutate(lon = sf::st_coordinates(.)[,1],
                lat = sf::st_coordinates(.)[,2]) 

    output$test <- renderLeaflet({
      acc %>%
        filter(local_auth %in% input$box_local_auth) %>%
        filter(month %in% input$box_month) %>%
        filter(year %in% input$box_year) %>%
        filter(severity %in% input$box_severity) %>%
        leaflet() %>%
        addTiles() %>%
        addCircleMarkers(
          radius = 5,
          color = ~pal(severity),
          label = acc$severity,
          popup=popupTable(popup)) %>%  
        addPolylines(data = map %>%
                      filter(LAD23NM %in% input$box_local_auth), color = "blue",fillOpacity = 0)

These images show the colors not following any logic:

[example 1](https://i.sstatic.net/82yVLxkT.png) enter image description here

1 Answer 1

0

It is not working because you are using label = acc$severity after filtering on acc. But acc$severity are the values of unfiltered acc. Just change it to ~severity. The colors are not wrong on the map, but the labels are.

Btw, it is easier to get answers if you provide a fully reproducible example like this :

library(leaflet)
library(shiny)
library(dplyr)


acc <- data.frame(
    id_r = c(1,2,3,4,5,6),
    severity = c("1. Fatal", "1. Fatal", "2. Serious", "2. Serious", "3. Slight", "3. Slight"),
    lat = c(1,1,1,1,1,1),
    long = c(1,2,3,4,5,6)
)

pal <- colorFactor(c("red", "navy", "green"), domain = c("1. Fatal", "2. Serious", "3. Slight"))

ui <- fluidPage(
    leafletOutput("test")
)
server <- function(input, output, session) {
    output$test <- renderLeaflet({
      acc %>%
        dplyr::filter(id_r %in% c(3, 4, 5, 6)) %>%
        leaflet() %>%
        addTiles() %>%
        addCircleMarkers(
          radius = 5,
          color = ~pal(severity),
          label = ~severity
          )
    })
}
shinyApp(ui = ui, server = server)

Not the answer you're looking for? Browse other questions tagged or ask your own question.