Search code examples
rr-leaflet

Coloring continuous data does not work on the map


Here is my data:

t <- data.frame(Name=c('A','B','C','D','E','F','G','H','I','J'),
                Longitude=c(151.2008,151.2458,150.8217,151.1215,150.8906,151.0660,150.8889,150.9188,150.4364,150.9982),
                Latitude=c(-33.90772,-33.89250,-34.05951,-33.97856,-34.40470,-33.90010,-33.92832,-33.90761,-34.44651,-33.79232),
                Diff=c(0.03,0.10,0.12,0.04,-0.12,0.34,-0.14,-0.01,0.21,-0.02),
                Diff1=c(30,100,120,40,-120,340,-140,-10,210,-20))

I want to use leaflet and R to draw this points on the map, and use the values of Diff / Diff1 for continuous color. Here is my code:

library(leaflet)
pal <- colorNumeric(
    palette = colorRampPalette(c('red','green')),
    domain = t$Diff1)
leaflet(data=t) %>%
    addTiles() %>%
    addCircles(lng=~Longitude,lat=~Latitude,radius=10,popup=~Name,color=~pal(Diff1))

I do not need a lot of different colors here. I just want the color could change from red to green as the increase of Diff1. But I only have red points on my map:

enter image description here

Another problem is no matter how I change the value of radius, the size of the data point does not change at all. I have no idea where I got wrong.

So, my questions are:

How to use coutinuous color? How to change the size of the points?


Solution

  • Try this (exluding the dataframe t below):

    library(leaflet)
    pal <- colorNumeric(
      palette = colorRampPalette(c('red', 'green'))(length(t$Diff1)), 
      domain = t$Diff1)
    
    leaflet(data = t) %>%
      addTiles() %>%
      addCircleMarkers(
        lng =  ~ Longitude,
        lat =  ~ Latitude,
        radius = ~ Diff * 100,
        popup =  ~ Name,
        color =  ~ pal(Diff1)
      )
    

    Remember, colorRampPalette actually returns a function, so you need to "crack" open the function with () when you are going to use it, like so:

    colorRampPalette(c('red', 'green'))(length(t$Diff1))
    # "#FF0000" "#E21C00" "#C63800" "#AA5500" "#8D7100" "#718D00" "#55AA00" "#38C600" "#1CE200" "#00FF00"
    

    Check the start and end colors (should be "red" and "green"):

    col2rgb("#FF0000")
    #       [,1]
    # red    255
    # green    0
    # blue     0
    
    col2rgb("#00FF00")
    #       [,1]
    # red      0
    # green  255
    # blue     0
    

    Yes, it did work out as expected.