I have an R Leaflet map showing cicles to mark the locations of industrial facilities. Some of these facilities have been assigned a risk score in the data ("RSEI_Score"), and others not (see working code below).

I have used an ifelse statement to assign a fixed radius to those without an RSEI score, and a square root function to make the radius of the remaining vary according to the score. Here is the line:

radius = ~ifelse(is.na(RSEI_Score), 300, sqrt(RSEI_Score) * 1.5),

However, some of the scores are very small, resulting in very small circles. I need to assign a minimum size of 300 to the circles that do have scores. I thought I could do that using "max" and setting a minimum, plus the sqrt value as maximum, but either I am doing it wrong, or it needs another technique. Does anyone know how to do it?

# Load libraries

# Read the CSV file
df <- read.csv("https://s3.us-east-2.amazonaws.com/ecotopia.today/Data/LA_TRI_RSEI_2021.csv")

# Convert WKT to sf geometry
df_sf <- st_as_sf(df, wkt = "WKT")

# Define color palette 
custom_palette <- colorRampPalette(c("#AF59BA", "#009ADE", "#F28522", "#FF1F5B"))

# Create Leaflet map with circles and color ramp
leaflet(df_sf) %>%
  addProviderTiles("Stadia.Outdoors") %>%
    radius = ~ifelse(is.na(RSEI_Score), 300, sqrt(RSEI_Score) * 1.5),
    color = "black",
    weight = 1,
    fillColor = ~ifelse(is.na(RSEI_Score), "#FFC61E", custom_palette(length(unique(df$RSEI_Score)))[seq_along(unique(df$RSEI_Score))]),
    fillOpacity = 0.7,
    popup = ~paste(as.character(PRIMARY_NAME), "<br>Risk factor: ", ifelse(is.na(RSEI_Score), "N/A", RSEI_Score)),
    label = ~paste(as.character(PRIMARY_NAME))
  ) %>%
  setView(lng = -90.95599, lat = 30.098563, zoom = 10)

1 Answer 1


In the end, I found two answers. First, the right way, using pmax and pmin:

# Define minimum and maximum sizes
min_size <- 5
max_size <- 40

# Set the radius with a minimum and maximum size
df_sf$radius <- ifelse(is.na(df_sf$RSEI_Score), min_size, sqrt(df_sf$RSEI_Score) * 0.02)
df_sf$radius <- pmax(min_size, pmin(df_sf$radius, max_size))

# use the radius value in addCirles options
radius = ~radius,

Next, the workaround whose effect I like better. It simply adds the minimum size of 300 to the square root values, ensuring that the points with values are always larger than those without:

    radius = ~ifelse(is.na(RSEI_Score), 300, 300 + sqrt(RSEI_Score) * 1.5),

I also realized I should be using markerCircles rather than just circles, but that's another story.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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