Get startedGet started for free

An interval scale example

Let's return to your plot of the proportion of the population that is between 18 and 24:

tm_shape(prop_by_age) +
  tm_raster("age_18_24", palette = vir) +
  tm_legend(position = c("right", "bottom"))

Your plot was problematic because most of the proportions fell in the lowest color level and consequently you didn't see much detail in your plot. One way to solve this problem is this: instead of breaking the range of your variable into equal length bins, you can break it into more useful categories.

Let's start by replicating the tmap default bins: five categories, cut using "pretty" breaks. Then you can try out a few of the other methods to cut a variable into intervals. Using the classIntervals() function directly gives you quick feedback on what the breaks will be, but the best way to try out a set of breaks is to plot them.

(As an aside, another way to solve this kind of problem is to look for a transform of the variable so that equal length bins of the transformed scale are more useful.)

This exercise is part of the course

Visualizing Geospatial Data in R

View Course

Exercise instructions

  • Call classIntervals() on values(prop_by_age[["age_18_24"]]) with n = 5 and style = "pretty". See the problem? 130,770 of your grid cells end up in the first bin.
  • Now call classIntervals() as above, but with style = "quantile".
  • Use the equisized bins by passing the n and style arguments into the tm_raster() layer of your plot.
  • Make a histogram of values(prop_by_age[["age_18_24"]]). Where would you make the breaks?
  • Create your own breaks in tm_raster() by specifying breaks = c(0.025, 0.05, 0.1, 0.2, 0.25, 0.3, 1).
  • Save your final plot as a leaflet plot using tmap_save() and the filename "prop_18-24.html".

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

mag <- viridisLite::magma(7)

library(classInt)

# Create 5 "pretty" breaks with classIntervals()



# Create 5 "quantile" breaks with classIntervals()



# Use 5 "quantile" breaks in tm_raster()
tm_shape(prop_by_age) +
  tm_raster("age_18_24", palette = mag) +
  tm_legend(position = c("right", "bottom"))

# Create histogram of proportions


# Use fixed breaks in tm_raster()
tm_shape(prop_by_age) +
  tm_raster("age_18_24", palette = mag,
    style = "fixed")

# Save your plot to "prop_18-24.html"
Edit and Run Code