Chapter 6 Visual variables

Visual variables are methods to translate information given in variables into many types of visualizations, including maps. Basic visual variables are color, size, and shape11. All of them can influence our perception and understanding of the presented information, therefore it is worth to understand when and how they can be used.

Basic visual variables and their representations on maps

FIGURE 6.1: Basic visual variables and their representations on maps

The use of visual variables on maps depends on two main things: (a) type of the presented variable, and (b) type of the map layer. Figure 6.1 shows examples of different visual variables. Color is the most universal visual variable. It can represent both qualitative (categorical) and quantitative (numerical) variables, and also we can color symbols, lines, or polygon fillings (sections 6.1.1 and 6.1.2). Sizes, on the other hand, should focus on quantitative variables. Small symbols could represent low values of a given variable, and the higher the value, the larger the symbol. Quantitative values of line data can be shown with the widths of the lines (section 6.2). The use of shapes usually should be limited to qualitative variables, and different shapes can represent different categories of points (section 6.3). Similarly, qualitative variables in lines can be presented by different line types. Values of polygons usually cannot be represented by either shapes or sizes, as these two features are connected to the geometries of the objects.

6.1 Colors

Colors, along with sizes and shapes, are the most often used to express values of attributes or their properties. Proper use of colors draws the attention of viewers and has a positive impact on the clarity of the presented information. On the other hand, poor decisions about colors can lead to misinterpretation of the map. Section 6.1.1 explains how colors are represented in R, how to decide which colors to use, and how to set different colors on maps. Section 6.1.2 focuses on how to specify color breaks and which types of scales styles are appropriate in different cases.

6.1.1 Color palettes

Colors in R are created based either on the color name or its hexadecimal form. R understands 657 built-in color names, such as "red", "lightblue" or "gray90", that are available using the colors() function. Hexadecimal form, on the other hand, can represent 16,777,216 unique colors. It consists of six-digits prefixed by the # (hash) symbol, where red, green, and blue values are each represented by two characters. In hexadecimal form, 00 is interpreted as 0.0 which means a lack of a particular color and FF means 1.0 and shows that the given color has maximal intensity. For example, #000000 represents black color, #FFFFFF white color, and #00FF00 green color.

Using a single color we are able to draw points, lines, polygon borders, or their areas. In that scenario, all of the elements will have the same color. However, often we want to represent different values in our data using different colors. This is a role for color palettes. A color palette is a set of colors used to distinguish the values of variables on maps.

Color palettes in R are usually stored as a vector of either color names or hexadecimal representations. For example, c("red", "green", "blue") or c("#66C2A5", "#FC8D62", "#8DA0CB"). It allows every one of us to create our own color palettes. However, the decision on how to decide which colors to use is not straightforward, and usually requires thinking about several aspects.

Firstly, what kind of variable we want to show? Is it a categorical variable where each value represents a group or a numerical variable in which values have order? The variable type impacts how it should be presented on the map. For categorical variables, each color usually should receive the same perceptual weight, which is done by using colors with the same brightness, but different hue. On the other hand, for numerical variables, we should easily understand which colors represent lower and which represent higher values. This is done by manipulating colorfulness and brightness. For example, low values could be presented by a blue color with low colorfulness and high brightness, and with growing values, colorfulness increases and brightness decreases.

Next consideration is related to how people perceive some colors. Usually, we want them to be able to preliminary understand which values the colors represent without looking at the legend – colors should be intuitive. For example, in the case of categorical variables representing land use, we usually want to use some type of blue color for rivers, green for trees, and white for ice. This idea also extends to numerical variables, where we should think about the association between colors and cultural values. The blue color is usually connected to cold temperature, while the red color is hot or can represent danger or something not good. However, we need to be aware that the connection between colors and cultural values varied between cultures.

Another thing to consider is to use a color palette that is accessible for people with color vision deficiencies (color blindness). There are several types of color blindness, with the red-green color blindness (deuteranomaly) being the most common. It is estimated that up to about 8% of the male population and about 0.5% of the female population in some regions of the world is color blind (Birch 2012; Sharpe et al. 1999).

The relation between the selected color palette and other map elements or the map background should be also taken into a consideration. For example, using a bright or dark background color on a map has an impact on how people will perceive different color palettes.

Generally, color palettes can be divided into three main types (Figure 6.2):

  • Categorical (also known as Qualitative) - used for presenting categorical information, for example, categories or groups. Every color in this type of palettes should receive the same perceptual weight, and the order of colors is meaningless. Categorical color palettes are usually limited to dozen or so different colors, as our eyes have problems with distinguishing a large number of different hues. Their use includes, for example, regions of the world or land cover categories.
  • Sequential - used for presenting continuous variables, in which order matters. Colors in this palette type changes from low to high (or vice versa), which is usually underlined by luminance differences (light-dark contrasts). Sequential palettes can be found in maps of GDP, population density, elevation, and many others.
  • Diverging - used for presenting continuous variables, but where colors diverge from a central neutral value to two extremes. Therefore, in sense, they consist of two sequential palettes that meet in the midpoint value. Examples of diverging palettes include maps where a certain temperature or median value of household income is use as the midpoint. It can also be used on maps to represent difference or change as well.
Examples of three main types of color palettes: categorical, sequential, and diverging

FIGURE 6.2: Examples of three main types of color palettes: categorical, sequential, and diverging

Gladly, a lot of work has been put on creating color palettes that are grounded in the research of perception and design. Currently, several dozens of R packages contain hundreds of color palettes. The most popular among them are RColorBrewer (Neuwirth 2014) and viridis (Garnier 2018). RColorBrewer builds upon a set of perceptually ordered color palettes (Harrower and Brewer 2003) and the associated website at https://colorbrewer2.org. The website not only presents all of the available color palettes, but also allow to filter them based on their properties, such as being colorblind safe or print-friendly. The viridis package has five color palettes are perceptually-uniform and suitable for people with color blindness. Four palettes is this package (“viridis”, “magma”, “plasma”, and “inferno”) are derived from the work on the color palettes for the matplotlib Python library. The last one, “cividis”, is based on the work of Nuñez, Anderton, and Renslow (2018).

RColorBrewer::brewer.pal(7, "RdBu")
#> [1] "#B2182B" "#EF8A62" "#FDDBC7" "#F7F7F7" "#D1E5F0"
#> [6] "#67A9CF" "#2166AC"
viridis::viridis(7)
#> [1] "#440154FF" "#443A83FF" "#31688EFF" "#21908CFF"
#> [5] "#35B779FF" "#8FD744FF" "#FDE725FF"

In the last few years, the grDevices package that is an internal part of R, have received several improvements over color palette handling.12 It includes creation of hcl.colors() and palette.colors(). The hcl.colors() function incorporates color palettes from several R packages, including RColorBrewer, viridis, rcartocolor (CARTO 2019; Nowosad 2018), and scico (Crameri 2018; Pedersen and Crameri 2020). You can get the list of available palette names for hcl.colors() using the hcl.pals() function and visualize all of the palettes with colorspace::hcl_palettes(plot = TRUE). The palette.colors() function adds several palettes for categorical data. It includes "Okabe-Ito" suited for color vision deficiencies or "Polychrome 36" that has 36 unique colors (Coombes et al. 2019). You can find the available names of the palettes for this function using palette.pals()

grDevices::hcl.colors(7, "Oslo")
#> [1] "#FCFCFC" "#C2CEE8" "#86A2D3" "#3C79C0" "#275182"
#> [6] "#132B48" "#040404"
grDevices::palette.colors(7, "Okabe-Ito")
#>       black      orange     skyblue bluishgreen 
#>   "#000000"   "#E69F00"   "#56B4E9"   "#009E73" 
#>      yellow        blue  vermillion 
#>   "#F0E442"   "#0072B2"   "#D55E00"

One of the most widely used color palettes is “rainbow” (the rainbow() function in R). It was inspired by colors of rainbows - a set of seven colors going from red to violet. However, this palette has a number of disadvantages, including irregular changes in brightness affecting its interpretation or being unsuitable for people with color vision deficiencies (Borland and Taylor Ii 2007; Stauffer et al. 2015; Quinan et al. 2019). Depending on a given situation, there are many palettes better suited for visualization than “rainbow”, including sequential "viridis" and "ag_Sunset" or diverging "Purple-Green" and "Fall". All of them can be created with the grDevices::hcl.colors() function. More examples showing alternatives to the “rainbow” palette are in the documentation of the colorspace package at https://colorspace.r-forge.r-project.org/articles/endrainbow.html (Zeileis et al. 2019).

By default, the tmap package attempts to identify the type of the used variable. Based on the result, it selects one of the build-in palettes: categorical "Set3", sequential "YlOrBr", or diverging "RdYlGn" (Figure 6.3).

tm_shape(worldvector) + 
  tm_polygons("life_expectancy")

It also offers three main ways to specify color palettes using the palette argument: (1) a vector of colors, (2) a palette function, or (3) one of the build-in names (Figure 6.3). A vector of colors can be specified using color names or hexadecimal representations (Figure 6.3). Importantly, the length of the provided vector does not need to be equal to the number of colors in the map legend. tmap automatically interpolates new colors in the case when a smaller number of colors is provided.

tm_shape(worldvector) +
  tm_polygons("life_expectancy", palette = c("yellow", "darkgreen"))

Another approach is to provide the output of a palette function (Figure 6.3). In the example below, we derived seven colors from "ag_GrnYl" palette. This palette goes from green colors to yellow ones, however, we wanted to reverse the order of this palette. Thus, we also used the rev() function here.

tm_shape(worldvector) +
  tm_polygons("life_expectancy", palette = rev(hcl.colors(7, "ag_GrnYl")))

The last approach is to use one of the names of color palettes build-in in tmap (Figure 6.3). In this example, we used the "YlGn" palette that goes from yellow to green.

tm_shape(worldvector) +
  tm_polygons("life_expectancy", palette = "YlGn")

You can find all of the named color palettes using an interactive app with tmaptools::palette_explorer(). It is also possible to reverse the order of any named color palette by using the - prefix. Therefore, "-YlGn" will return a palette going from green to yellow.

Examples of four ways of specifying color palettes: (A) default sequential color palette, (B) palette created based on provided vector of colors, (C) palette created using the hcl.colors() function, and (D) one of the build-in palettes.

FIGURE 6.3: Examples of four ways of specifying color palettes: (A) default sequential color palette, (B) palette created based on provided vector of colors, (C) palette created using the hcl.colors() function, and (D) one of the build-in palettes.

The default color palette for positive numerical variables is "YlOrBr" as seen in Figure 6.4:A. On the other hand, when the given variable has both negative and positive values, then tmap uses the "RdYlGn" color palette, with red colors below the midpoint value, yellow color around the midpoint value, and green colors above the midpoint value. The use of diverging color palettes can be adjusted using the midpoint argument. It has a value of 0 as the default, however, it is possible to change it to any other value. For example, we want to create a map that shows countries with life expectancy below and above the median life expectancy of about 73 years. To do that, we just need to set the midpoint argument to this value (Figure 6.4:B).

tm_shape(worldvector) +
  tm_polygons(col = "life_expectancy", midpoint = 73)
Examples of (A) a map with the default sequential color palette and (B) a map with the diverging color palette around the midpoint value of 73.

FIGURE 6.4: Examples of (A) a map with the default sequential color palette and (B) a map with the diverging color palette around the midpoint value of 73.

Now the countries with low life expectancy are presented with red colors, yellow areas represent countries with life expectancy around the median value (the midpoint in our case), and the countries with high life expectancy are represented by green colors.

The above examples all contain several polygons with missing values of a given variable. Objects with missing values are, by default, represented by gray color and a related legend label Missing. However, it is possible to change this color with the colorNA argument and its label with textNA.

tmap has a special way to set colors for categorical maps manually. It works by providing a named vector to the palette argument. In this vector, names of the categories from the categorical variable are the vector names, and specified colors are the vector values. You can see it in the example below, where we plot the "region_un" categorical variable (Figure 6.5). Each category in this variable (e.g., "Africa") has a new, connected to it color (e.g., "#11467b").

tm_shape(worldvector) + 
  tm_polygons("wb_region", 
    palette = c(
      "Latin America & Caribbean" = "#11467b",
      "Europe & Central Asia" = "#ffd14d", 
      "Middle East & North Africa" = "#86909a", 
      "Sub-Saharan Africa" = "#14909a",
      "East Asia & Pacific" = "#7fbee9",
      "South Asia" = "#df5454",
      "North America" = "#7b1072")
    )
#> Some legend labels were too wide. These labels have been resized to 0.61, 0.62. Increase legend.width (argument of tm_layout) to make the legend wider and therefore the labels larger.
An example of a categorical map with manually selected colors.

FIGURE 6.5: An example of a categorical map with manually selected colors.

Finally, visualized colors can be additionally modified. It includes setting the alpha argument that represents the transparency of the used colors. By default, the colors are not transparent at all as the value of alpha is 1. However, we can decrease this value to 0 - total transparency. The alpha argument is useful in two ways: one - it allows us to see-through some large objects (e.g., some points below the polygons or a hillshade map behind the colored raster of elevation), second - it makes colors more subtle.

6.1.2 Color scale styles

tm_polygons() accepts three ways of specifying the fill color with the col argument13. The first one is to fill all polygons with the same color. This happens when we provide a single color value, either as a color name or its hexadecimal form (section 6.1.1) (Figure 6.6).

tm_shape(worldvector) +
  tm_polygons(col = "lightblue")
Example of a map with all polygons filled with the same color.

FIGURE 6.6: Example of a map with all polygons filled with the same color.

The second way of specifying the fill color is to provide a name of the column (variable) we want to visualize. tmap behaves differently depending on the input variable type, but always automatically adds a map legend. In general, a categorical map is created when the provided variable contains characters, factors, or is of the logical type. However, when the provided variable is numerical, then it is possible to create either a discrete or a continuous map.

An example of a categorical map can be seen in Figure 6.7. We created it by providing a character variable’s name, "wb_region", in the col argument14.

tm_shape(worldvector) +
  tm_polygons(col = "wb_region")
Example of a map in which polygons are colored based on the values of a categorical variable.

FIGURE 6.7: Example of a map in which polygons are colored based on the values of a categorical variable.

It is possible to change the names of legend labels with the labels argument. However, to change the order of legend labels, we need to provide an ordered factor variable’s name instead of a character one. As mentioned in the section 6.1.1, we can also change the used color palette with the palette argument.

Discrete maps, on the other hand, represent continuous numerical variables using discrete class intervals. In other words, values are divided into several groups based on their properties. Several approaches can be used to convert continuous variables to discrete ones, and each of them could result in different groups of values. tmap has 14 different methods to create discrete maps that can be specified with the style argument. Most of them (except "log10_pretty") use the classInt package (Bivand 2020) in the background, therefore some additional information can be found in the ?classIntervals function’s documentation.

By default, the "pretty" style is used (Figure 6.8:A). This style creates breaks that are whole numbers and spaces them evenly.15

tm_shape(worldvector) +
  tm_polygons(col = "gdp_per_cap")

It is also possible to indicate the desired number of classes using the n argument, when the "pretty" style is used. While not every n is possible depending on the input values, tmap will try to create a number of classes as close to possible to the preferred one.

The next approach is to manually select the limits of each break with the breaks function (Figure 6.8:B). This can be useful when we have some pre-defined breaks, or when we want to compare values between several maps. It expects threshold values for each break, therefore, if we want to have three breaks, we need to provide four thresholds. Additionally, we can add a label to each break with the labels argument.

tm_shape(worldvector) +
  tm_polygons(col = "gdp_per_cap", 
              breaks = c(0, 10000, 30000, 111000),
              labels = c("low", "medium", "high"))

Another approach is to create breaks automatically using one of many existing classification methods. Three basic methods are "equal", "sd", and "quantile" styles. Let’s consider a variable with 100 observations ranging from 0 to 10. The "equal" style divides the range of values into n equal-sized intervals. This style works well when the values change fairly continuously and do not contain any outliers. In tmap, we can specify the number of classes with the n argument or the number of classes will be computed automatically . For example, when we set n to 4, then our breaks will represent four classes ranging from 0 to 2.5, 2.5 to 5, 5 to 7.5, and 7.5 to 10. The "sd" style represents how much values of a given variable varies from its mean, with each interval having a constant width of the standard deviation. This style is used when it is vital to show how values relate to the mean. The "quantile" style creates several classes with exactly the same number of objects (e.g., spatial features), but having intervals of various lengths. This method has an advantage or not having any empty classes or classes with too few or too many values. However, the resulting intervals from the "quantile" style can often be misleading, with very different values located in the same class.

To create classes that, on the one hand, contain similar values, and on the other hand, are different from the other classes, we can use some optimization method. The most common optimization method used in cartography is the Jenks optimization method implemented at the "jenks" style (Figure 6.8:C).

tm_shape(worldvector) +
  tm_polygons(col = "gdp_per_cap", 
              style = "jenks")

The Fisher method (style = "fisher") has a similar role, which creates groups with maximized homogeneity (Fisher 1958). A different approach is used by the dpih style, which uses kernel density estimations to select the width of the intervals (Wand 1997). You can visit ?KernSmooth::dpih for more details.

Another group of classification methods uses existing clustering methods. It includes k-means clustering ("kmeans"), bagged clustering ("bclust"), and hierarchical clustering ("hclust").

Finally, there are a few methods created to work well for a variable with a heavy-tailed distribution, including "headtails" and "log10_pretty". The "headtails" style is an implementation of the head/tail breaks method aimed at heavily right-skewed data. In it, values of the given variable are being divided around the mean into two parts, and the process continues iteratively for the values above the mean (the head) until the head part values are no longer heavy-tailed distributed (Jiang 2013). The "log10_pretty" style uses a logarithmic base-10 transformation (Figure 6.8:D). In this style, each class starts with a value ten times larger than the beginning of the previous class. In other words, each following class shows us the next order of magnitude. This style allows for a better distinction between low, medium, and high values. However, maps with logarithmically transformed variables are usually less intuitive for the readers and require more attention from them.

tm_shape(worldvector) +
  tm_polygons(col = "gdp_per_cap", 
              style = "log10_pretty")
Examples of four methods of creating discrete maps: (A) default method (‘pretty’), (B) the ‘fixed’ method with manually set breaks, (C) the ‘jenks’ method, and (D) the ‘log10_pretty’ method.

FIGURE 6.8: Examples of four methods of creating discrete maps: (A) default method (‘pretty’), (B) the ‘fixed’ method with manually set breaks, (C) the ‘jenks’ method, and (D) the ‘log10_pretty’ method.

Continuous maps also represent continuous numerical variables, but without any discrete class intervals (Figure 6.9). Three continuous methods exist in tmap: cont, order, and log10. Values change increasingly in all of them, but they differ in the relations between values and colors.

The cont style creates a smooth, linear gradient. In other words, the change in values is proportionally related to the change in colors. We can see that in Figure 6.9:A, where the value change from 20,000 to 40,000 has a similar impact on the color scale as the value change from 40,000 to 60,000. The cont style is similar to the pretty one, where the values also change linearly. The main difference between these styles is that we can see differences between, for example, values of 45,000 and 55,000 in the former, while both values have exactly the same color in the later one. The cont style works well in situations where there is a large number of objects in vectors or a large number of cells in rasters, and where the values change continuously (do not have many outliers).

tm_shape(worldvector) +
  tm_polygons(col = "gdp_per_cap",
              style = "cont")

However, when the presented variable is skewed or have some outliers, we can use either order or log10 style. The order style also uses a smooth gradient with a large number of colors, but the values on the legend do not change linearly (Figure 6.9:B). It is fairly analogous to the quantile style, with the values on a color scale that divides a dataset into several equal-sized groups.

tm_shape(worldvector) +
  tm_polygons(col = "gdp_per_cap",
              style = "order")

Finally, the log10 style is the continuous equivalent of the log10_pretty style (Figure 6.9:C).

tm_shape(worldvector) +
  tm_polygons(col = "gdp_per_cap",
              style = "log10")
Examples of three methods of creating continuous maps: (A) the ‘cont’ method, (B) the ‘order’ method, and (C) the ‘log10’ method.

FIGURE 6.9: Examples of three methods of creating continuous maps: (A) the ‘cont’ method, (B) the ‘order’ method, and (C) the ‘log10’ method.

The tm_polygons() also offer a third way of specifying the fill color. When the col argument is set to "MAP_COLORS" then polygons will be colored in such a way that adjacent polygons do not get the same color (Figure 6.10).

tm_shape(worldvector) +
  tm_polygons(col = "MAP_COLORS")

In this case, it is also possible to change the default colors with the palette argument, but also to activate the internal algorithm to search for a minimal number of colors for visualization by setting minimize = TRUE.

Example of a map with adjacent polygons having different colors.

FIGURE 6.10: Example of a map with adjacent polygons having different colors.

All of the color scale styles mentioned above work not only for tm_polygons() - they can be also applied for tm_symbols() (and its derivatives - tm_dots(), tm_bubbles(), tm_squares()), tm_lines(), tm_fill(), and tm_raster(). The col argument colors symbols’ fillings in tm_symbols(), lines in tm_lines(), and cells in tm_rasters().

6.2 Sizes

ei_points = read_sf("data/easter_island/ei_points.gpkg")
volcanos = subset(ei_points, type == "volcano")

Differences in sizes between objects are relatively easy to recognize on maps. Sizes can be used for points, lines (line widths), or text to represent quantitative (numerical) variables, where small values are related to small objects and large values are presented by large objects. Large sizes can be also used to attract viewers’ attention.

By default, tmaps present points, lines, or text objects of the same size. For example, tm_symbols() returns a map where each object is a circle with a consistent size16. We can change the sizes of all objects using the size argument (Figure 6.11:A).

tm_shape(volcanos) +
 tm_symbols(size = 0.5) 

On the other hand, if we provide the name of the numerical variable in the size argument (e.g., "elevation"), then symbol sizes are scaled proportionally to the provided values. Objects with small values will be represented by smaller circles, while larger values will be represented by larger circles (Figure 6.11:B).

tm_shape(volcanos) +
 tm_symbols(size = "elevation") 

We can adjust size legend breaks with sizes.legend and the corresponding labels with sizes.legend.labels (Figure 6.11:C). However, this only modifies the legend, not the related objects.

tm_shape(volcanos) +
 tm_symbols(size = "elevation",
            title.size = "Elevation",
            sizes.legend = c(100, 600),
            sizes.legend.labels = c("low", "high")) 

For example in the above code, we just show examples of how symbols with population of one million and 10 million looks like on the map.

Examples of three approaches for changing sizes of symbols: (A) all symbols have a consistent size of 0.5, (B) sizes of symbols depends on the values of the elevation variable, (C) sizes of symbols have a manually created legend.

FIGURE 6.11: Examples of three approaches for changing sizes of symbols: (A) all symbols have a consistent size of 0.5, (B) sizes of symbols depends on the values of the elevation variable, (C) sizes of symbols have a manually created legend.

Widths of the lines can represent values of numerical variables for line data similar to sizes of the symbols for point data. The lwd argument in tm_lines() creates thin lines for small values and thick lines for large values of the given variable (Figure 6.12).

ei_roads = read_sf("data/easter_island/ei_roads.gpkg")
tm_shape(ei_roads) + 
  tm_lines(lwd = "strokelwd")
Example of a map where lines' widths represent values of the corresponding lines.

FIGURE 6.12: Example of a map where lines’ widths represent values of the corresponding lines.

In the above example, values of the "strokelwd" are divided into four groups and represented by four line widths. Lines’ thickness can be change using the scale argument, where the value of 1 is the default, and increasing this values increases lines’ thickness. Also, similarly to the last example of the tm_symbols above, it is possible to modify the lines width legend, by changing its title (title.lwd), categories (lwd.legend), and their names (lwd.legend.labels).

Text labels have a role to name features on a map or just to highlight some of them. Usually, the size of text labels is consistent for the same spatial objects. However, text labels can be also used to represent the values of some numerical variables. Figure 6.13 shows an example, in which text labels show names of different volcanos areas, while their sizes are related to their elevations.

tm_shape(volcanos) +
  tm_text(text = "name", size = "elevation") +
  tm_layout(legend.outside = TRUE)
Example of a map where text sizes represent elevations of the volcanos.

FIGURE 6.13: Example of a map where text sizes represent elevations of the volcanos.

6.3 Shapes

Shapes allow representing different categories of point data. They can be very generic, e.g., circle or square, just to be able to differentiate between categories, but often we use symbols that we associate with different types of features. For example, we use the letter P for parking lots, I for information centers, an airplane symbol for airports, or a bus symbol for bus stops.

To use different shapes, we should use the shape argument in the tm_symbols() function. It expects the name of the categorical variable.

tm_shape(ei_points) +
  tm_symbols(shape = "type",
             title.shape = "Type:",
             shapes.labels = c("Cave entrance", "Peak", "Volcano"))

By default, tmap uses symbols of filled circle, square, diamond, point-up triangle, and point-down triangle17. However, it is also possible to customize used symbols, their title, and labels. Legend title related to shapes is modified with the title.shape argument, while their labels use the shapes.lables argument.

Shapes can be specified with the shapes argument, that allows using one of three options. The first one is a numeric value that specifies the plotting character of the symbol18. A complete list of available symbols and their corresponding numbers is in the ?pch function’s documentation.

tm_shape(ei_points) +
  tm_symbols(shape = "type",
             shapes = c(0, 2, 5))

Second option is to use a grob object.

# library(grid)
# library(ggplotify)
library(ggplot2)

# p1 = as.grob(~barplot(1:10))
# p2 = as.grob(expression(plot(rnorm(10), yaxt = "n", xaxt = "n", ann = FALSE, bty = "n")))
# p3 = as.grob(function() plot(sin, yaxt = "n", xaxt = "n", ann = FALSE, bty = "n"))
p4 = ggplotGrob(ggplot(data.frame(x = 1:5, y = 1:5), aes(x, y)) + geom_point() + theme_void())
tm_shape(ei_points) +
  tm_symbols(shape = "type",
             shapes = list(p4, p4, p4),
             border.col = NULL)

The last possibility is to use an icon specification created with the tmap_icons() function, that uses any png images. The tmap_icons() function accepts a vector of file paths or urls, and also allows setting the width and height of the icon. In our example, we have three distinct groups, therefore we need to create new icons based on three images - icon1.png, icon2.png, and icon3.png in this case.

my_icons = tmap_icons(c("images/icon1.png", 
                        "images/icon2.png", 
                        "images/icon3.png"))

Now, we can use the prepared icons in the shapes argument (Figure 6.14:D).

tm_shape(ei_points) +
  tm_symbols(shape = "type",
             shapes = my_icons,
             border.col = NULL)
Examples of two maps with different symbols: (A) default symbols, (B) user-defined symbols, (C) grob objects, and (D) icons.

FIGURE 6.14: Examples of two maps with different symbols: (A) default symbols, (B) user-defined symbols, (C) grob objects, and (D) icons.

6.4 Mixing visual variables

The values of a given variable can be expressed by different categorical or sequential colors in polygons. Lines can be also colored by one variable, but also widths of the lines can represent values of another quantitative variable. When we use symbols, then we are able to use colors for one qualitative or quantitative variable, sizes for a quantitative variable, and shapes for another qualitative variable. Therefore, it is possible to mix some visual variables for symbols and lines. This section shows only some possible examples of mixing visual variables.

Figure 6.15:A shows symbols, which sizes are scales based on the sv variable and they are colored using the values from elevation. This can be set with the size and col arguments.

tm_shape(ei_points) +
  tm_symbols(size = "sv", col = "elevation")

We can also modify all of the visual variables using the additional arguments explained in the previous sections. For example, we can set the color style (style), color palette (palette), or specify shapes (shapes) (Figure 6.15:B).

tm_shape(ei_points) +
  tm_symbols(col = "elevation", style = "cont", palette = "Greens",
             shape = "type", shapes = c(23, 24, 25))

When we use plot polygons, there is only one visual variable we can use - color. Therefore, changing of map legend’s title in functions like tm_polygons() or tm_fill() is done with the title argument. However, what to do when we have two or more visual variables in, for example, tm_symbols()? In these cases, we need to specify a corresponding suffix for each title argument. The color title is set with title.col, size title with title.size, and shape title with title.size (Figure 6.15:C).

tm_shape(ei_points) +
 tm_symbols(size = "elevation", title.size = "Elevation:",
            shape = "type", title.shape = "Type:")
Examples of maps using two visual variables at the same time: (A) size and color, (B) color and shape, (C) size and shape.

FIGURE 6.15: Examples of maps using two visual variables at the same time: (A) size and color, (B) color and shape, (C) size and shape.

For line data, we can present its qualitative and quantitative variables using colors and quantitative variables using sizes (line widths) (Figure 6.16).

A map using two visual variables, color and size (line width), at the same time.

FIGURE 6.16: A map using two visual variables, color and size (line width), at the same time.

References

Birch, Jennifer. 2012. “Worldwide Prevalence of Red-Green Color Deficiency.” Journal of the Optical Society of America A 29 (3): 313. https://doi.org/10/ggkw82.

Bivand, Roger. 2020. ClassInt: Choose Univariate Class Intervals. https://CRAN.R-project.org/package=classInt.

Borland, David, and Russell Taylor Ii. 2007. “Rainbow Color Map (Still) Considered Harmful.” IEEE Computer Graphics and Applications 27 (2): 14–17. https://doi.org/10/cf7nms.

CARTO. 2019. “CARTOColors Data-Driven Color Schemes.” https://carto.com/carto-colors/.

Coombes, Kevin R., Guy Brock, Zachary B. Abrams, and Lynne V. Abruzzo. 2019. “Polychrome : Creating and Assessing Qualitative Palettes with Many Colors.” Journal of Statistical Software 90 (Code Snippet 1). https://doi.org/10/ggkqvs.

Crameri, Fabio. 2018. “Geodynamic Diagnostics, Scientific Visualisation and StagLab 3.0.” Geoscientific Model Development 11 (6): 2541–62. https://doi.org/10/gdt4tg.

Fisher, Walter D. 1958. “On Grouping for Maximum Homogeneity.” Journal of the American Statistical Association, 10. https://doi.org/10/gkb5sf.

Garnier, Simon. 2018. Viridis: Default Color Maps from ’Matplotlib’. https://CRAN.R-project.org/package=viridis.

Harrower, Mark, and Cynthia A. Brewer. 2003. “ColorBrewer.Org: An Online Tool for Selecting Colour Schemes for Maps.” The Cartographic Journal 40 (1): 27–37. https://doi.org/10/ch4c57.

Jiang, Bin. 2013. “Head/Tail Breaks: A New Classification Scheme for Data with a Heavy-Tailed Distribution.” The Professional Geographer 65 (3): 482–94. https://doi.org/10/f24r6j.

Neuwirth, Erich. 2014. RColorBrewer: ColorBrewer Palettes. https://CRAN.R-project.org/package=RColorBrewer.

Nowosad, Jakub. 2018. ’CARTOColors’ Palettes. https://nowosad.github.io/rcartocolor.

Nuñez, Jamie R., Christopher R. Anderton, and Ryan S. Renslow. 2018. “Optimizing Colormaps with Consideration for Color Vision Deficiency to Enable Accurate Interpretation of Scientific Data.” Edited by Jesús Malo. PLOS ONE 13 (7): e0199239. https://doi.org/10/gdzkg4.

Pedersen, Thomas Lin, and Fabio Crameri. 2020. Scico: Colour Palettes Based on the Scientific Colour-Maps. https://CRAN.R-project.org/package=scico.

Quinan, P. S., L. M. Padilla, S. H. Creem-Regehr, and M. Meyer. 2019. “Examining Implicit Discretization in Spectral Schemes.” Computer Graphics Forum 38 (3): 363–74. https://doi.org/10/ggb9nd.

Sharpe, Lindsay T, Andrew Stockman, Herbert Jägle, and Jeremy Nathans. 1999. “Opsin Genes, Cone Photopigments, Color Vision, and Color Blindness.” In Color Vision: From Genes to Perception, edited by T Gegenfurtner and Lindsay T Sharpe, 50. Cambridge: Cambridge University Press.

Stauffer, Reto, Georg J. Mayr, Markus Dabernig, and Achim Zeileis. 2015. “Somewhere over the Rainbow: How to Make Effective Use of Colors in Meteorological Visualizations.” Bulletin of the American Meteorological Society 96 (2): 203–16. https://doi.org/10/f3sttk.

Wand, M. P. 1997. “Data-Based Choice of Histogram Bin Width.” The American Statistician 51 (1): 59. https://doi.org/10/fvsfdb.

Zeileis, Achim, Jason C. Fisher, Kurt Hornik, Ross Ihaka, Claire D. McWhite, Paul Murrell, Reto Stauffer, and Claus O. Wilke. 2019. “colorspace: A Toolbox for Manipulating and Assessing Colors and Palettes.” ArXiv 1903.06490. arXiv.org E-Print Archive. http://arxiv.org/abs/1903.06490.


  1. Other visual variables include position, orientation, and texture.↩︎

  2. Learn more about them at https://developer.r-project.org/Blog/public/2019/04/01/hcl-based-color-palettes-in-grdevices/ and https://developer.r-project.org/Blog/public/2019/11/21/a-new-palette-for-r/index.html.↩︎

  3. To see and compare examples of every color scale style from tmap visit https://geocompr.github.io/post/2019/tmap-color-scales/.↩︎

  4. The tm_polygons(col = "region_un", style = "cat") code is run automatically in this case.↩︎

  5. For more information visit the ?pretty() function documentation↩︎

  6. The default value of size is 1, which corresponds to the area of symbols that have the same height as one line of text.↩︎

  7. They are represented in R by numbers from 21 to 25.↩︎

  8. However, this is not supported for the “view” mode.↩︎