Search code examples
rtmap

tmap in R is ignoring my "breaks" argument for discrete buckets


I am making a world heatmap from a dataset where the values of one country are -1 and the rest are values from 0 to 10. I tried to make 5 discrete buckets by making a palette of 5 colors and a breaks argument with 6 integers in a vector.

robin <- "+proj=robin +lon_0=0 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs"

map = tm_shape(mapdata, projection = robin, bbox = boundaries) +
  tm_polygons("Sum.of.increase", # style = "fixed",
              breaks = c(-Inf, 0, .5, 1, 2, Inf),
              palette = c("white","#FF7C80", "wheat1", "#ADDC9C", "#6AC04A"), colorNA = "grey",
              legend.show = TRUE) + 
  tm_layout (frame = FALSE, bg.color = "transparent") + 
#  tmap_options(max.categories = 5)
map

I can see from the legend that it seems to be totally disregarding my buckets.

legend

I have tried with more values in the breaks vector, I've added style = fixed, and I've added tmap_options max.categories to no avail.

Commenting out the line with the breaks argument results in the exact same output map/legend.

Debugging details: Desired behavior: The map and legend should reflect that the buckets I have defined are respected: -Infinity to 0, 0 to 0.5, 0.5 to 1, 1 to 2, 2 to infinity

R.Version()
$platform
[1] "x86_64-w64-mingw32"

$arch
[1] "x86_64"

$os
[1] "mingw32"

$crt
[1] "ucrt"

$system
[1] "x86_64, mingw32"

$status
[1] ""

$major
[1] "4"

$minor
[1] "2.1"

$year
[1] "2022"

$month
[1] "06"

$day
[1] "23"

$`svn rev`
[1] "82513"

$language
[1] "R"

$version.string
[1] "R version 4.2.1 (2022-06-23 ucrt)"

$nickname
[1] "Funny-Looking Kid"

Solution

  • I figured out the issue: the variable being plotted was class "character" rather than numeric.

    To diagnose: summary(mapdata$Sum.of.increase)

    Results:

    Length     Class      Mode 
    173 character character
    

    To fix:

    mapdata$Sum.of.increase = as.numeric(mapdata$Sum.of.increase)

    Confirmation:

    > summary(mapdata$Sum.of.increase)
       Min. 1st Qu.  Median    Mean 3rd Qu.    Max.    NA's 
    -1.0000  0.4068  0.7621  2.1974  1.2964 10.0000      37 
    

    To summarize, if some function is ignoring your breaks, make sure the variable is numeric as apparently breaks don't work on strings even though R can interpret and graph them.