Learn R Programming

tmaptools (version 3.3)

map_coloring: Map coloring

Description

Color the polygons of a map such that adjacent polygons have different colors. This function returns the color indices

Usage

map_coloring(x, algorithm = "greedy", ncols = 8, minimize = FALSE, ...)

Value

A vector of color indices.

Arguments

x

Either a shape (i.e. a sf or SpatialPolygons(DataFrame) (sp package) object), or an adjacency list.

algorithm

currently, only "greedy" is implemented.

ncols

number of colors. By default 8.

minimize

logical that determines whether algorithm will search for a minimal number of colors. If FALSE, the ncols colors will be picked by a random procedure.

...

to catch deprecated arguments palette and contrast. See details.

Details

As of tmaptools 3.3, the deprecated color functions get_brewer_pal and palette_explorer, have been removed. These have been replaced c4a and c4a_gui respectively from the package cols4all. Therefore, map_coloring will return color indices and will ignore the input arguments palette and contrast. See example.

Examples

Run this code
if (require(tmap) && require(cols4all)) {
    data(World)

    ## using cols4all directly
    indices <- map_coloring(World)
    pal <- c4a("brewer.set2", n = max(indices))
    World$color = pal[indices]
    tm_shape(World) +
        tm_polygons("color", fill.scale = tm_scale_asis()) +
        tm_crs("auto")

    # using map_coloring via "MAP_COLORS" in tmap
    tm_shape(World) +
        tm_polygons("MAP_COLORS", tm_scale(values = "brewer.set2")) +
        tm_crs("auto")

    # other example
    data(NLD_prov, NLD_muni)
    tm_shape(NLD_prov) +
    	tm_fill("name",
    	        fill.legend = tm_legend_hide()) +
    tm_shape(NLD_muni) +
    	tm_polygons("MAP_COLORS",
    	            fill_alpha = .25,
    	            fill.scale = tm_scale(values = "brewer.greys")) +
    tm_shape(NLD_prov) +
    	tm_borders(lwd=2) +
    	tm_text("name", options = opt_tm_text(shadow = TRUE)) +
    tm_title("Dutch provinces and\nmunicipalities", bg.color="white")
}

Run the code above in your browser using DataLab