r plotly draw map in 3d plane

Making maps with R

Prerequisites

  • This chapter requires the following packages that nosotros have already been using:
  • In addition, information technology uses the post-obit visualization packages (also install shiny if you desire to develop interactive mapping applications):

Introduction

A satisfying and of import aspect of geographic research is communicating the results. Map making — the art of cartography — is an ancient skill that involves communication, intuition, and an chemical element of inventiveness. Static mapping in R is straightforward with the plot() function, as we saw in Section 2.2.3. Information technology is possible to create advanced maps using base R methods (Murrell 2016). The focus of this affiliate, however, is cartography with dedicated map-making packages. When learning a new skill, it makes sense to gain depth-of-knowledge in 1 area earlier branching out. Map making is no exception, hence this chapter'due south coverage of one package (tmap) in depth rather than many superficially.

In addition to beingness fun and creative, cartography also has important practical applications. A advisedly crafted map can be the best way of communicating the results of your piece of work, but poorly designed maps tin get out a bad impression. Common design problems include poor placement, size and readability of text and careless pick of colors, equally outlined in the fashion guide of the Journal of Maps. Furthermore, poor map making can hinder the advice of results (Brewer 2015):

Amateur-looking maps tin undermine your audience'due south ability to understand important information and weaken the presentation of a professional data investigation.

Maps accept been used for several thousand years for a wide variety of purposes. Historic examples include maps of buildings and land ownership in the Former Babylonian dynasty more than than 3000 years agone and Ptolemy's world map in his masterpiece Geography nearly 2000 years ago (Talbert 2014).

Map making has historically been an activity undertaken only by, or on behalf of, the aristocracy. This has changed with the emergence of open source mapping software such as the R packet tmap and the 'print composer' in QGIS which enable anyone to brand loftier-quality maps, enabling 'citizen science'. Maps are also often the best way to present the findings of geocomputational research in a manner that is accessible. Map making is therefore a critical part of geocomputation and its accent not only on describing, simply also changing the world.

This affiliate shows how to brand a wide range of maps. The side by side section covers a range of static maps, including aesthetic considerations, facets and inset maps. Sections 9.iii to 9.5 cover blithe and interactive maps (including spider web maps and mapping applications). Finally, Section 9.6 covers a range of alternative map-making packages including ggplot2 and cartogram.

Static maps

Static maps are the nigh common type of visual output from geocomputation. Standard formats include .png and .pdf for raster and vector outputs respectively. Initially, static maps were the only type of maps that R could produce. Things advanced with the release of sp (see Pebesma and Bivand 2005) and many techniques for map making have been developed since then. However, despite the innovation of interactive mapping, static plotting was yet the emphasis of geographic data visualisation in R a decade later (Cheshire and Lovelace 2015).

The generic plot() part is frequently the fastest fashion to create static maps from vector and raster spatial objects (encounter sections ii.2.3 and 2.3.3). Sometimes, simplicity and speed are priorities, particularly during the development phase of a projection, and this is where plot() excels. The base R approach is also extensible, with plot() offering dozens of arguments. Some other approach is the grid package which allows low level control of static maps, equally illustrated in Affiliate 14 of Murrell (2016). This section focuses on tmap and emphasizes the important artful and layout options.

tmap is a powerful and flexible map-making parcel with sensible defaults. It has a concise syntax that allows for the creation of attractive maps with minimal code which will exist familiar to ggplot2 users. Information technology also has the unique capability to generate static and interactive maps using the aforementioned code via tmap_mode(). Finally, it accepts a wider range of spatial classes (including raster objects) than alternatives such equally ggplot2 (see the vignettes tmap-getstarted and tmap-changes-v2, as well as Tennekes (2018), for further documentation).

tmap basics

Like ggplot2, tmap is based on the idea of a 'grammar of graphics' (Wilkinson and Wills 2005). This involves a separation between the input information and the aesthetics (how data are visualised): each input dataset tin exist 'mapped' in a range of unlike ways including location on the map (divers by information's geometry), colour, and other visual variables. The bones building block is tm_shape() (which defines input data, raster and vector objects), followed by one or more than layer elements such every bit tm_fill() and tm_dots(). This layering is demonstrated in the clamper below, which generates the maps presented in Effigy ix.ane:

New Zealand's shape plotted with fill (left), border (middle) and fill and border (right) layers added using tmap functions.

FIGURE ix.1: New Zealand's shape plotted with fill (left), border (middle) and fill and border (right) layers added using tmap functions.

The object passed to tm_shape() in this instance is nz, an sf object representing the regions of New Zealand (see Section ii.two.one for more on sf objects). Layers are added to represent nz visually, with tm_fill() and tm_borders() creating shaded areas (left panel) and edge outlines (eye panel) in Figure 9.1, respectively.

This is an intuitive approach to map making: the mutual task of calculation new layers is undertaken by the addition operator +, followed by tm_*(). The asterisk (*) refers to a wide range of layer types which have self-explanatory names including fill, borders (demonstrated higher up), bubbles, text and raster (see help("tmap-element") for a full listing). This layering is illustrated in the right console of Figure ix.1, the outcome of adding a border on elevation of the fill up layer.

qtm() is a handy office to create quick thematic thouaps (hence the snappy name). It is concise and provides a adept default visualization in many cases: qtm(nz), for example, is equivalent to tm_shape(nz) + tm_fill() + tm_borders(). Further, layers tin be added concisely using multiple qtm() calls, such every bit qtm(nz) + qtm(nz_height). The disadvantage is that information technology makes aesthetics of individual layers harder to command, explaining why we avoid teaching it in this chapter.

Map objects

A useful feature of tmap is its ability to store objects representing maps. The lawmaking clamper below demonstrates this by saving the last plot in Figure 9.1 equally an object of course tmap (note the use of tm_polygons() which condenses tm_fill() + tm_borders() into a unmarried function):

map_nz tin be plotted later, for example by adding boosted layers (as shown below) or simply running map_nz in the console, which is equivalent to impress(map_nz).

New shapes can exist added with + tm_shape(new_obj). In this case new_obj represents a new spatial object to be plotted on elevation of preceding layers. When a new shape is added in this mode, all subsequent aesthetic functions refer to it, until another new shape is added. This syntax allows the creation of maps with multiple shapes and layers, as illustrated in the next code chunk which uses the function tm_raster() to plot a raster layer (with alpha set to make the layer semi-transparent):

Building on the previously created map_nz object, the preceding lawmaking creates a new map object map_nz1 that contains some other shape (nz_elev) representing average elevation across New Zealand (come across Figure ix.2, left). More shapes and layers can be added, equally illustrated in the code chunk below which creates nz_water, representing New Zealand'due south territorial waters, and adds the resulting lines to an existing map object.

There is no limit to the number of layers or shapes that can exist added to tmap objects. The same shape tin can fifty-fifty be used multiple times. The last map illustrated in Figure 9.2 is created by adding a layer representing high points (stored in the object nz_height) onto the previously created map_nz2 object with tm_dots() (encounter ?tm_dots and ?tm_bubbles for details on tmap'due south indicate plotting functions). The resulting map, which has iv layers, is illustrated in the right-manus panel of Effigy 9.2:

A useful and little known feature of tmap is that multiple map objects can be arranged in a single 'metaplot' with tmap_arrange(). This is demonstrated in the lawmaking chunk below which plots map_nz1 to map_nz3, resulting in Figure 9.2.

Maps with additional layers added to the final map of Figure 8.1.

FIGURE 9.ii: Maps with additional layers added to the final map of Figure 8.ane.

More elements can also be added with the + operator. Artful settings, still, are controlled by arguments to layer functions.

Aesthetics

The plots in the previous section demonstrate tmap'southward default aesthetic settings. Greyness shades are used for tm_fill() and tm_bubbles() layers and a continuous blackness line is used to represent lines created with tm_lines(). Of course, these default values and other aesthetics tin exist overridden. The purpose of this section is to testify how.

There are two principal types of map aesthetics: those that change with the information and those that are abiding. Different ggplot2, which uses the helper role aes() to represent variable aesthetics, tmap accepts aesthetic arguments directly. To map a variable to an aesthetic, laissez passer its cavalcade proper name to the respective argument, and to fix a stock-still artful, laissez passer the desired value instead.42 The most commonly used aesthetics for make full and border layers include colour, transparency, line width and line type, set with col, alpha, lwd, and lty arguments, respectively. The bear upon of setting these with fixed values is illustrated in Figure 9.3.

The impact of changing commonly used fill and border aesthetics to fixed values.

FIGURE 9.3: The impact of irresolute commonly used fill and edge aesthetics to fixed values.

Like base R plots, arguments defining aesthetics can as well receive values that vary. Different the base R code beneath (which generates the left panel in Figure 9.4), tmap aesthetic arguments will not accept a numeric vector:

                                  plot                  (                  st_geometry                  (                  nz                  ), col                  =                  nz                  $                  Land_area                  )                  # works                  tm_shape                  (                  nz                  )                  +                  tm_fill                  (col                  =                  nz                  $                  Land_area                  )                  # fails                  #> Mistake: Fill argument neither colors nor valid variable name(southward)                              

Instead col (and other aesthetics that can vary such as lwd for line layers and size for point layers) requires a character string naming an attribute associated with the geometry to exist plotted. Thus, i would attain the desired outcome as follows (plotted in the right-hand panel of Effigy 9.4):

Comparison of base (left) and tmap (right) handling of a numeric color field. Comparison of base (left) and tmap (right) handling of a numeric color field.

FIGURE 9.4: Comparison of base of operations (left) and tmap (correct) handling of a numeric color field.

An important statement in functions defining aesthetic layers such as tm_fill() is title, which sets the title of the associated fable. The following code chunk demonstrates this functionality by providing a more than attractive proper noun than the variable name Land_area (note the employ of expression() to create superscript text):

Color settings

Color settings are an important part of map blueprint. They can have a major impact on how spatial variability is portrayed equally illustrated in Figure 9.5. This shows iv ways of coloring regions in New Zealand depending on median income, from left to right (and demonstrated in the code clamper below):

  • The default setting uses 'pretty' breaks, described in the next paragraph
  • breaks allows you to manually prepare the breaks
  • northward sets the number of bins into which numeric variables are categorized
  • palette defines the color scheme, for example BuGn

Illustration of settings that affect color settings. The results show (from left to right): default settings, manual breaks, n breaks, and the impact of changing the palette.

Figure 9.5: Analogy of settings that affect colour settings. The results evidence (from left to right): default settings, transmission breaks, n breaks, and the affect of irresolute the palette.

Another way to change color settings is by altering color suspension (or bin) settings. In addition to manually setting breaks tmap allows users to specify algorithms to automatically create breaks with the style argument. Here are six of the most useful break styles:

  • mode = "pretty", the default setting, rounds breaks into whole numbers where possible and spaces them evenly;
  • manner = "equal" divides input values into bins of equal range and is appropriate for variables with a uniform distribution (not recommended for variables with a skewed distribution as the resulting map may end-upwards having footling color diversity);
  • style = "quantile" ensures the aforementioned number of observations fall into each category (with the potential downside that bin ranges tin vary widely);
  • manner = "jenks" identifies groups of similar values in the information and maximizes the differences between categories;
  • way = "cont" (and "order") present a big number of colors over continuous color fields and are particularly suited for continuous rasters ("order" can help visualize skewed distributions);
  • style = "cat" was designed to correspond categorical values and assures that each category receives a unique color.

Illustration of different binning methods set using the style argument in tmap.

Effigy 9.6: Illustration of dissimilar binning methods set using the style statement in tmap.

Although style is an statement of tmap functions, in fact it originates as an argument in classInt::classIntervals() — meet the help page of this function for details.

Palettes define the color ranges associated with the bins and determined by the breaks, n, and style arguments described above. The default color palette is specified in tm_layout() (see Section 9.2.5 to larn more); nevertheless, it could be quickly inverse using the palette argument. It expects a vector of colors or a new color palette proper name, which tin can exist selected interactively with tmaptools::palette_explorer(). You can add a - as prefix to opposite the palette society.

There are 3 main groups of color palettes: categorical, sequential and diverging (Effigy nine.vii), and each of them serves a different purpose. Categorical palettes consist of easily distinguishable colors and are most appropriate for categorical information without any item club such as land names or land cover classes. Colors should be intuitive: rivers should be blue, for example, and pastures green. Avert too many categories: maps with large legends and many colors tin can exist uninterpretable.43

The second grouping is sequential palettes. These follow a gradient, for example from light to nighttime colors (light colors tend to represent lower values), and are appropriate for continuous (numeric) variables. Sequential palettes can be single (Blues go from light to night blue, for example) or multi-colour/hue (YlOrBr is slope from light yellowish to dark-brown via orangish, for example), every bit demonstrated in the lawmaking clamper below — output not shown, run the code yourself to meet the results!

The last grouping, diverging palettes, typically range betwixt iii distinct colors (purple-white-green in Figure 9.7) and are usually created past joining two single-color sequential palettes with the darker colors at each finish. Their main purpose is to visualize the difference from an important reference point, east.g., a certain temperature, the median household income or the mean probability for a drought outcome. The reference point's value tin be adjusted in tmap using the midpoint argument.

Examples of categorical, sequential and diverging palettes.

FIGURE 9.vii: Examples of categorical, sequential and diverging palettes.

There are 2 important principles for consideration when working with colors: perceptibility and accessibility. Firstly, colors on maps should match our perception. This means that certain colors are viewed through our feel and also cultural lenses. For example, light-green colors ordinarily represent vegetation or lowlands and blue is connected with water or cool. Color palettes should too be easy to empathise to effectively convey information. It should be clear which values are lower and which are higher, and colors should alter gradually. This property is non preserved in the rainbow colour palette; therefore, we propose avoiding it in geographic information visualization (Borland and Taylor Ii 2007). Instead, the viridis color palettes, also available in tmap, can be used. Secondly, changes in colors should be accessible to the largest number of people. Therefore, it is important to use colorblind friendly palettes as oft as possible.44

Layouts

The map layout refers to the combination of all map elements into a cohesive map. Map elements include among others the objects to be mapped, the championship, the scale bar, margins and aspect ratios, while the color settings covered in the previous section chronicle to the palette and interruption-points used to touch on how the map looks. Both may result in subtle changes that can have an every bit large impact on the impression left by your maps.

Boosted elements such as northward arrows and scale bars have their own functions: tm_compass() and tm_scale_bar() (Figure 9.8).

Map with additional elements - a north arrow and scale bar.

FIGURE 9.8: Map with additional elements - a north arrow and calibration bar.

tmap too allows a wide variety of layout settings to be changed, some of which, produced using the post-obit code (see args(tm_layout) or ?tm_layout for a total list), are illustrated in Figure ix.9:

Layout options specified by (from left to right) title, scale, bg.color and frame arguments.

Effigy nine.ix: Layout options specified past (from left to right) title, scale, bg.color and frame arguments.

The other arguments in tm_layout() provide control over many more than aspects of the map in relation to the sheet on which information technology is placed. Here are some useful layout settings (some of which are illustrated in Figure 9.ten):

  • Frame width (frame.lwd) and an option to let double lines (frame.double.line)
  • Margin settings including outer.margin and inner.margin
  • Font settings controlled by fontface and fontfamily
  • Legend settings including binary options such as fable.prove (whether or not to evidence the fable) legend.only (omit the map) and legend.outside (should the legend go outside the map?), equally well equally multiple choice settings such equally legend.position
  • Default colors of aesthetic layers (aes.color), map attributes such as the frame (attr.colour)
  • Colour settings controlling sepia.intensity (how yellowy the map looks) and saturation (a color-grayscale)

Illustration of selected layout options.

FIGURE 9.ten: Illustration of selected layout options.

The touch of changing the color settings listed in a higher place is illustrated in Figure ix.11 (meet ?tm_layout for a full list).

Illustration of selected color-related layout options.

Figure nine.xi: Illustration of selected color-related layout options.

Beyond the depression-level control over layouts and colors, tmap also offers high-level styles, using the tm_style() part (representing the 2d meaning of 'style' in the parcel). Some styles such as tm_style("cobalt") consequence in stylized maps, while others such as tm_style("gray") make more subtle changes, as illustrated in Figure 9.12, created using the code below (run into 08-tmstyles.R):

Selected tmap styles.

Figure 9.12: Selected tmap styles.

A preview of predefined styles can be generated by executing tmap_style_catalogue(). This creates a folder called tmap_style_previews containing nine images. Each image, from tm_style_albatross.png to tm_style_white.png, shows a faceted map of the world in the corresponding style. Notation: tmap_style_catalogue() takes some time to run.

Faceted maps

Faceted maps, likewise referred to as 'small multiples', are equanimous of many maps arranged side-by-side, and sometimes stacked vertically (Meulemans et al. 2017). Facets enable the visualization of how spatial relationships change with respect to another variable, such as time. The changing populations of settlements, for case, tin be represented in a faceted map with each console representing the population at a particular moment in fourth dimension. The time dimension could be represented via another aesthetic such as color. Notwithstanding, this risks cluttering the map considering it will involve multiple overlapping points (cities exercise non tend to move over fourth dimension!).

Typically all individual facets in a faceted map contain the same geometry information repeated multiple times, one time for each column in the aspect information (this is the default plotting method for sf objects, see Chapter ii). However, facets tin also represent shifting geometries such as the evolution of a bespeak pattern over time. This utilise case of faceted plot is illustrated in Figure 9.thirteen.

Faceted map showing the top 30 largest urban agglomerations from 1970 to 2030 based on population projections by the United Nations.

FIGURE 9.13: Faceted map showing the top 30 largest urban agglomerations from 1970 to 2030 based on population projections by the United nations.

The preceding code chunk demonstrates key features of faceted maps created with tmap:

  • Shapes that do not have a facet variable are repeated (the countries in globe in this case)
  • The past argument which varies depending on a variable (yr in this case).
  • The nrow/ncol setting specifying the number of rows and columns that facets should exist arranged into
  • The gratuitous.coords parameter specifying if each map has its own bounding box

In addition to their utility for showing changing spatial relationships, faceted maps are likewise useful as the foundation for animated maps (encounter Section 9.3).

Inset maps

An inset map is a smaller map rendered within or adjacent to the primary map. It could serve many different purposes, including providing a context (Figure 9.14) or bringing some non-contiguous regions closer to ease their comparison (Figure 9.15). They could be also used to focus on a smaller area in more than item or to embrace the aforementioned area as the map, but representing a unlike topic.

In the example below, nosotros create a map of the central part of New Zealand'southward Southern Alps. Our inset map will evidence where the primary map is in relation to the whole New Zealand. The first pace is to ascertain the area of interest, which can be done by creating a new spatial object, nz_region.

In the 2nd step, nosotros create a base map showing the New Zealand'southward Southern Alps expanse. This is a place where the about of import message is stated.

The third stride consists of the inset map creation. Information technology gives a context and helps to locate the expanse of interest. Importantly, this map needs to clearly indicate the location of the main map, for instance by stating its borders.

Finally, nosotros combine the two maps using the function viewport() from the filigree package, the first arguments of which specify the center location (ten and y) and a size (width and summit) of the inset map.

Inset map providing a context - location of the central part of the Southern Alps in New Zealand.

Figure nine.fourteen: Inset map providing a context - location of the central part of the Southern Alps in New Zealand.

Inset map can be saved to file either by using a graphic device (see Section eight.8) or the tmap_save() part and its arguments - insets_tm and insets_vp.

Inset maps are also used to create one map of non-contiguous areas. Probably, the most often used example is a map of the The states, which consists of the contiguous Us, Hawaii and Alaska. It is very important to find the best projection for each private inset in these types of cases (run across Affiliate 7 to learn more). We tin employ Usa National Atlas Equal Surface area for the map of the face-to-face U.s.a. by putting its EPSG lawmaking in the projection argument of tm_shape().

The remainder of our objects, hawaii and alaska, already take proper projections; therefore, we just need to create two separate maps:

The final map is created by combining and arranging these three maps:

                                  us_states_map                  impress                  (                  hawaii_map, vp                  =                  grid                  ::                  viewport                  (                  0.35,                  0.ane, width                  =                  0.ii, height                  =                  0.1                  )                  )                  impress                  (                  alaska_map, vp                  =                  grid                  ::                  viewport                  (                  0.xv,                  0.15, width                  =                  0.iii, height                  =                  0.3                  )                  )                              

Map of the United States.

Effigy 9.15: Map of the United States.

The code presented above is compact and can be used as the basis for other inset maps but the results, in Figure 9.xv, provide a poor representation of the locations of Hawaii and Alaska. For a more in-depth approach, see the us-map vignette from the geocompkg.

Animated maps

Faceted maps, described in Section 9.2.half dozen, can show how spatial distributions of variables change (e.thou., over time), but the approach has disadvantages. Facets become tiny when there are many of them. Furthermore, the fact that each facet is physically separated on the screen or folio ways that subtle differences between facets tin exist hard to find.

Blithe maps solve these issues. Although they depend on digital publication, this is becoming less of an event as more and more content moves online. Blithe maps can withal enhance newspaper reports: you can always link readers to a web-page containing an animated (or interactive) version of a printed map to assist make it come live. There are several means to generate animations in R, including with animation packages such equally gganimate, which builds on ggplot2 (see Section 9.6). This section focusses on creating animated maps with tmap because its syntax volition exist familiar from previous sections and the flexibility of the approach.

Effigy 9.xvi is a simple example of an animated map. Unlike the faceted plot, information technology does not squeeze multiple maps into a single screen and allows the reader to see how the spatial distribution of the world's most populous agglomerations evolve over time (encounter the book'southward website for the animated version).

Animated map showing the top 30 largest urban agglomerations from 1950 to 2030 based on population projects by the United Nations. Animated version available online at: geocompr.robinlovelace.net.

FIGURE ix.xvi: Animated map showing the peak 30 largest urban agglomerations from 1950 to 2030 based on population projects past the United Nations. Animated version available online at: geocompr.robinlovelace.net.

The animated map illustrated in Figure 9.16 can be created using the same tmap techniques that generate faceted maps, demonstrated in Section 9.two.6. In that location are two differences, however, related to arguments in tm_facets():

  • along = "year" is used instead of by = "yr".
  • costless.coords = False, which maintains the map extent for each map iteration.

These additional arguments are demonstrated in the subsequent code chunk:

The resulting urb_anim represents a set of split maps for each year. The final phase is to combine them and save the result as a .gif file with tmap_animation(). The following command creates the animation illustrated in Figure 9.16, with a few elements missing, that we volition add in during the exercises:

Some other illustration of the power of animated maps is provided in Figure 9.17. This shows the development of states in the Usa, which first formed in the east then incrementally to the westward and finally into the interior. Code to reproduce this map can exist establish in the script 08-usboundaries.R.

Animated map showing population growth, state formation and boundary changes in the United States, 1790-2010. Animated version available online at geocompr.robinlovelace.net.

Effigy 9.17: Animated map showing population growth, state germination and boundary changes in the United states, 1790-2010. Animated version bachelor online at geocompr.robinlovelace.net.

Interactive maps

While static and blithe maps can enliven geographic datasets, interactive maps tin can take them to a new level. Interactivity tin take many forms, the most common and useful of which is the ability to pan around and zoom into any function of a geographic dataset overlaid on a 'spider web map' to show context. Less avant-garde interactivity levels include popups which appear when you lot click on different features, a kind of interactive label. More advanced levels of interactivity include the power to tilt and rotate maps, equally demonstrated in the mapdeck example below, and the provision of "dynamically linked" sub-plots which automatically update when the user pans and zooms (Pezanowski et al. 2018).

The near of import type of interactivity, nonetheless, is the display of geographic data on interactive or 'slippy' spider web maps. The release of the leaflet packet in 2022 revolutionized interactive web map creation from within R and a number of packages have built on these foundations adding new features (e.k., leaflet.extras) and making the cosmos of web maps equally simple as creating static maps (e.g., mapview and tmap). This section illustrates each approach in the opposite gild. We will explore how to make slippy maps with tmap (the syntax of which we take already learned), mapview and finally leaflet (which provides low-level control over interactive maps).

A unique feature of tmap mentioned in Department ix.two is its power to create static and interactive maps using the same code. Maps can exist viewed interactively at any point past switching to view mode, using the command tmap_mode("view"). This is demonstrated in the lawmaking beneath, which creates an interactive map of New Zealand based on the tmap object map_nz, created in Section 9.ii.ii, and illustrated in Figure ix.18:

Figure 9.18: Interactive map of New Zealand created with tmap in view mode. Interactive version available online at: geocompr.robinlovelace.net.

Now that the interactive mode has been 'turned on', all maps produced with tmap will launch (another style to create interactive maps is with the tmap_leaflet function). Notable features of this interactive mode include the ability to specify the basemap with tm_basemap() (or tmap_options()) as demonstrated below (issue not shown):

An impressive and fiddling-known feature of tmap'southward view way is that it as well works with faceted plots. The statement sync in tm_facets() tin can be used in this case to produce multiple maps with synchronized zoom and pan settings, as illustrated in Figure 9.19, which was produced by the following code:

                              world_coffee                =                left_join                (                world,                coffee_data, by                =                "name_long"                )                facets                =                c                (                "coffee_production_2016",                "coffee_production_2017"                )                tm_shape                (                world_coffee                )                +                tm_polygons                (                facets                )                +                tm_facets                (nrow                =                1, sync                =                TRUE                )                          

Faceted interactive maps of global coffee production in 2022 and 2022 in sync, demonstrating tmap's view mode in action.

Figure nine.19: Faceted interactive maps of global coffee production in 2022 and 2022 in sync, demonstrating tmap's view mode in activity.

Switch tmap dorsum to plotting way with the same function:

                              tmap_mode                (                "plot"                )                #> tmap mode set to plotting                          

If you are not proficient with tmap, the quickest way to create interactive maps may be with mapview. The post-obit 'ane liner' is a reliable way to interactively explore a broad range of geographic information formats:

Illustration of mapview in action.

FIGURE nine.20: Illustration of mapview in activity.

mapview has a curtailed syntax yet is powerful. By default, it provides some standard GIS functionality such as mouse position information, attribute queries (via pop-ups), scale bar, and zoom-to-layer buttons. Information technology offers advanced controls including the ability to 'flare-up' datasets into multiple layers and the addition of multiple layers with + followed by the proper name of a geographic object. Additionally, information technology provides automatic coloring of attributes (via argument zcol). In essence, it can exist considered a data-driven leaflet API (see below for more data well-nigh leaflet). Given that mapview ever expects a spatial object (sf, Spatial*, Raster*) as its beginning argument, it works well at the stop of piped expressions. Consider the post-obit case where sf is used to intersect lines and polygons and so is visualized with mapview (Figure 9.21).

Using mapview at the end of a sf-based pipe expression.

FIGURE 9.21: Using mapview at the cease of a sf-based piping expression.

I of import thing to keep in mind is that mapview layers are added via the + operator (like to ggplot2 or tmap). This is a frequent gotcha in piped workflows where the primary binding operator is %>%. For further information on mapview, see the package'due south website at: r-spatial.github.io/mapview/.

There are other ways to create interactive maps with R. The googleway parcel, for instance, provides an interactive mapping interface that is flexible and extensible (meet the googleway-vignette for details). Another approach by the same writer is mapdeck, which provides access to Uber's Deck.gl framework. Its utilize of WebGL enables information technology to interactively visualize big datasets (up to millions of points). The packet uses Mapbox access tokens, which you must register for earlier using the packet.

Note that the post-obit block assumes the access token is stored in your R environment as MAPBOX=your_unique_key. This can be added with edit_r_environ() from the usethis packet.

A unique characteristic of mapdeck is its provision of interactive 'two.5d' perspectives, illustrated in Figure 9.22. This ways yous tin can tin can pan, zoom and rotate effectually the maps, and view the data 'extruded' from the map. Effigy ix.22, generated past the following code chunk, visualizes road traffic crashes in the United kingdom, with bar peak respresenting casualties per area.

                              library                (                mapdeck                )                set_token                (                Sys.getenv                (                "MAPBOX"                )                )                crash_data                =                read.csv                (                "https://git.io/geocompr-mapdeck"                )                crash_data                =                na.omit                (                crash_data                )                ms                =                mapdeck_style                (                "nighttime"                )                mapdeck                (style                =                ms, pitch                =                45, location                =                c                (                0,                52                ), zoom                =                4                )                %>%                add_grid                (data                =                crash_data, lat                =                "lat", lon                =                "lng", cell_size                =                thou,          elevation_scale                =                50, layer_id                =                "grid_layer",          colour_range                =                viridisLite                ::                plasma                (                6                )                )                          

Map generated by mapdeck, representing road traffic casualties across the UK. Height of 1 km cells represents number of crashes.

Figure 9.22: Map generated past mapdeck, representing road traffic casualties beyond the United kingdom. Height of 1 km cells represents number of crashes.

In the browser y'all tin can zoom and elevate, in add-on to rotating and tilting the map when pressing Cmd/Ctrl. Multiple layers tin can be added with the %>% operator, equally demonstrated in the mapdeck vignette.

Mapdeck besides supports sf objects, equally can be seen by replacing the add_grid() function call in the preceding lawmaking chunk with add_polygon(information = lnd, layer_id = "polygon_layer"), to add polygons representing London to an interactive tilted map.

Last merely non least is leaflet which is the about mature and widely used interactive mapping package in R. leaflet provides a relatively low-level interface to the Leaflet JavaScript library and many of its arguments tin can be understood past reading the documentation of the original JavaScript library (see leafletjs.com).

Leaflet maps are created with leaflet(), the result of which is a leaflet map object which can exist piped to other leaflet functions. This allows multiple map layers and control settings to be added interactively, equally demonstrated in the code below which generates Figure 9.23 (see rstudio.github.io/leaflet/ for details).

The leaflet package in action, showing cycle hire points in London. See interactive version [online](https://geocompr.github.io/img/leaflet.html).

Effigy 9.23: The leaflet package in action, showing bicycle hire points in London. Come across interactive version online.

Mapping applications

The interactive web maps demonstrated in Department 9.four can make it. Careful choice of layers to display, base-maps and pop-ups tin be used to communicate the main results of many projects involving geocomputation. But the web mapping approach to interactivity has limitations:

  • Although the map is interactive in terms of panning, zooming and clicking, the code is static, meaning the user interface is fixed
  • All map content is generally static in a web map, meaning that web maps cannot scale to handle large datasets easily
  • Additional layers of interactivity, such a graphs showing relationships betwixt variables and 'dashboards' are difficult to create using the web-mapping approach

Overcoming these limitations involves going beyond static web mapping and towards geospatial frameworks and map servers. Products in this field include GeoDjango (which extends the Django web framework and is written in Python), MapGuide (a framework for developing web applications, largely written in C++) and GeoServer (a mature and powerful map server written in Coffee). Each of these (specially GeoServer) is scalable, enabling maps to exist served to thousands of people daily — bold there is sufficient public interest in your maps! The bad news is that such server-side solutions require much skilled developer fourth dimension to set-up and maintain, frequently involving teams of people with roles such equally a dedicated geospatial database administrator (DBA).

The good news is that web mapping applications can at present be rapidly created using shiny, a bundle for converting R lawmaking into interactive web applications. This is thanks to its support for interactive maps via functions such equally renderLeaflet(), documented on the Shiny integration department of RStudio'southward leaflet website. This section gives some context, teaches the basics of shiny from a web mapping perspective and culminates in a full-screen mapping application in less than 100 lines of code.

The way shiny works is well documented at shiny.rstudio.com. The two primal elements of a shiny app reflect the duality common to nigh web awarding development: 'front end' (the bit the user sees) and 'back finish' code. In shiny apps, these elements are typically created in objects named ui and server inside an R script named app.R, which lives in an 'app folder'. This allows web mapping applications to be represented in a single file, such as the coffeeApp/app.R file in the book's GitHub repo.

In shiny apps these are often divide into ui.R (short for user interface) and server.R files, naming conventions used by shiny-server, a server-side Linux application for serving shiny apps on public-facing websites. shiny-server likewise serves apps divers by a single app.R file in an 'app folder'. Larn more at: https://github.com/rstudio/shiny-server.

Before because large apps, information technology is worth seeing a minimal example, named 'lifeApp', in activity.45 The code below defines and launches — with the command shinyApp() — a lifeApp, which provides an interactive slider allowing users to brand countries appear with progressively lower levels of life expectancy (see Figure nine.24):

Screenshot showing minimal example of a web mapping application created with shiny.

Effigy 9.24: Screenshot showing minimal example of a spider web mapping application created with shiny.

The user interface (ui) of lifeApp is created by fluidPage(). This contains input and output 'widgets' — in this case, a sliderInput() (many other *Input() functions are available) and a leafletOutput(). These are arranged row-wise past default, explaining why the slider interface is placed directly above the map in Figure 9.24 (see ?cavalcade for adding content column-wise).

The server side (server) is a office with input and output arguments. output is a list of objects containing elements generated by render*() function — renderLeaflet() which in this instance generates output$map. Input elements such as input$life referred to in the server must relate to elements that exist in the ui — defined past inputId = "life" in the lawmaking higher up. The function shinyApp() combines both the ui and server elements and serves the results interactively via a new R procedure. When you move the slider in the map shown in Figure 9.24, you are really causing R lawmaking to re-run, although this is hidden from view in the user interface.

Building on this basic case and knowing where to find assist (encounter ?shiny), the best way forward now may exist to finish reading and start programming! The recommended next footstep is to open the previously mentioned CycleHireApp/app.R script in an IDE of option, modify it and re-run information technology repeatedly. The example contains some of the components of a spider web mapping application implemented in shiny and should 'shine' a calorie-free on how they behave.

The CycleHireApp/app.R script contains shiny functions that go beyond those demonstrated in the simple 'lifeApp' example. These include reactive() and observe() (for creating outputs that respond to the user interface — come across ?reactive) and leafletProxy() (for modifying a leaflet object that has already been created). Such elements are critical to the creation of web mapping applications implemented in shiny. A range of 'events' can be programmed including avant-garde functionality such equally drawing new layers or subsetting data, equally described in the shiny section of RStudio'due south leaflet website.

In that location are a number of ways to run a shiny app. For RStudio users, the simplest manner is probably to click on the 'Run App' button located in the tiptop right of the source pane when an app.R, ui.R or server.R script is open. shiny apps can besides be initiated by using runApp() with the first argument being the folder containing the app lawmaking and data: runApp("CycleHireApp") in this case (which assumes a folder named CycleHireApp containing the app.R script is in your working directory). Yous tin can likewise launch apps from a Unix command line with the control Rscript -eastward 'shiny::runApp("CycleHireApp")'.

Experimenting with apps such as CycleHireApp volition build not only your knowledge of web mapping applications in R, but besides your applied skills. Irresolute the contents of setView(), for instance, will change the starting bounding box that the user sees when the app is initiated. Such experimentation should not exist done at random, but with reference to relevant documentation, starting with ?shiny, and motivated by a desire to solve bug such as those posed in the exercises.

shiny used in this fashion tin can make prototyping mapping applications faster and more than accessible than ever before (deploying shiny apps is a divide topic beyond the scope of this affiliate). Even if your applications are eventually deployed using different technologies, shiny undoubtedly allows web mapping applications to exist developed in relatively few lines of code (76 in the example of CycleHireApp). That does not finish shiny apps getting rather big. The Propensity to Cycle Tool (Percent) hosted at percent.bike, for example, is a national mapping tool funded by the UK's Department for Transport. The PCT is used by dozens of people each mean solar day and has multiple interactive elements based on more than g lines of lawmaking (Lovelace et al. 2017).

While such apps undoubtedly accept time and effort to develop, shiny provides a framework for reproducible prototyping that should aid the development procedure. 1 potential problem with the ease of developing prototypes with shiny is the temptation to start programming besides early, earlier the purpose of the mapping application has been envisioned in detail. For that reason, despite advocating shiny, we recommend starting with the longer established technology of a pen and newspaper equally the commencement phase for interactive mapping projects. This way your prototype web applications should be express not by technical considerations, but by your motivations and imagination.

Effigy nine.25: Hire a bicycle App, a simple web mapping awarding for finding the closest cycle hiring station based on your location and requirement of cycles. Interactive version bachelor online at geocompr.robinlovelace.net.

Other mapping packages

tmap provides a powerful interface for creating a wide range of static maps (Department nine.2) and likewise supports interactive maps (Department nine.iv). But there are many other options for creating maps in R. The aim of this section is to provide a taster of some of these and pointers for additional resources: map making is a surprisingly active area of R package development, so in that location is more than to learn than can be covered here.

The most mature option is to utilize plot() methods provided by core spatial packages sf and raster, covered in Sections 2.ii.3 and 2.3.3, respectively. What we have non mentioned in those sections was that plot methods for raster and vector objects tin be combined when the results draw onto the aforementioned plot area (elements such as keys in sf plots and multi-ring rasters will interfere with this). This behavior is illustrated in the subsequent code chunk which generates Figure ix.26. plot() has many other options which tin can exist explored by following links in the ?plot assist page and the sf vignette sf5.

                              g                =                st_graticule                (                nz, lon                =                c                (                170,                175                ), lat                =                c                (                -                45,                -                40,                -                35                )                )                plot                (                nz_water, graticule                =                g, axes                =                True, col                =                "blue"                )                raster                ::                plot                (                nz_elev                /                1000, add                =                Truthful                )                plot                (                st_geometry                (                nz                ), add                =                TRUE                )                          

Map of New Zealand created with plot(). The legend to the right refers to elevation (1000 m above sea level).

FIGURE 9.26: Map of New Zealand created with plot(). The legend to the correct refers to elevation (1000 thousand higher up sea level).

Since version 2.3.0, the tidyverse plotting package ggplot2 has supported sf objects with geom_sf(). The syntax is similar to that used by tmap: an initial ggplot() call is followed by i or more layers, that are added with + geom_*(), where * represents a layer type such equally geom_sf() (for sf objects) or geom_points() (for points).

ggplot2 plots graticules by default. The default settings for the graticules can be overridden using scale_x_continuous(), scale_y_continuous() or coord_sf(datum = NA). Other notable features include the use of unquoted variable names encapsulated in aes() to indicate which aesthetics vary and switching information sources using the information argument, as demonstrated in the code chunk below which creates Figure 9.27:

Map of New Zealand created with ggplot2.

FIGURE 9.27: Map of New Zealand created with ggplot2.

An advantage of ggplot2 is that it has a strong user-community and many add-on packages. Expert additional resources tin can be institute in the open up source ggplot2 book (Wickham 2016) and in the descriptions of the multitude of 'ggpackages' such equally ggrepel and tidygraph.

Another do good of maps based on ggplot2 is that they can easily be given a level of interactivity when printed using the function ggplotly() from the plotly package. Try plotly::ggplotly(g1), for example, and compare the event with other plotly mapping functions described at: web log.cpsievert.me.

At the same time, ggplot2 has a few drawbacks. The geom_sf() function is not always able to create a desired legend to apply from the spatial data. Raster objects are also non natively supported in ggplot2 and need to exist converted into a data frame before plotting.

We have covered mapping with sf, raster and ggplot2 packages showtime because these packages are highly flexible, allowing for the creation of a wide range of static maps. Before we embrace mapping packages for plotting a specific type of map (in the next paragraph), information technology is worth because alternatives to the packages already covered for general-purpose mapping (Table 9.ane).

Tabular array 9.1: Selected full general-purpose mapping packages.
Package Title
cartography Thematic Cartography
ggplot2 Create Elegant Data Visualisations Using the Grammar of Graphics
googleway Accesses Google Maps APIs to Retrieve Information and Plot Maps
ggspatial Spatial Data Framework for ggplot2
leaflet Create Interactive Web Maps with Leaflet
mapview Interactive Viewing of Spatial Data in R
plotly Create Interactive Spider web Graphics via 'plotly.js'
rasterVis Visualization Methods for Raster Information
tmap Thematic Maps

Table 9.1 shows a range of mapping packages are available, and there are many others not listed in this tabular array. Of note is cartography, which generates a range of unusual maps including choropleth, 'proportional symbol' and 'menstruum' maps, each of which is documented in the vignette cartography.

Several packages focus on specific map types, as illustrated in Table 9.2. Such packages create cartograms that misconstrue geographical space, create line maps, transform polygons into regular or hexagonal grids, and visualize circuitous data on grids representing geographic topologies.

Tabular array 9.2: Selected specific-purpose mapping packages, with associated metrics.
Package Title
cartogram Create Cartograms with R
geogrid Turn Geospatial Polygons into Regular or Hexagonal Grids
geofacet 'ggplot2' Faceting Utilities for Geographical Data
earth Plot 2D and 3D Views of the Earth, Including Major Coastline
linemap Line Maps

All of the aforementioned packages, nonetheless, have dissimilar approaches for data preparation and map creation. In the next paragraph, we focus solely on the cartogram package. Therefore, nosotros suggest to read the linemap, geogrid and geofacet documentations to learn more than about them.

A cartogram is a map in which the geometry is proportionately distorted to correspond a mapping variable. Creation of this type of map is possible in R with cartogram, which allows for creating continuous and non-contiguous expanse cartograms. It is not a mapping package per se, simply it allows for construction of distorted spatial objects that could be plotted using whatever generic mapping package.

The cartogram_cont() function creates continuous area cartograms. It accepts an sf object and proper name of the variable (cavalcade) as inputs. Additionally, information technology is possible to alter the intermax argument - maximum number of iterations for the cartogram transformation. For example, nosotros could represent median income in New Zeleand'southward regions as a continuous cartogram (the correct-hand panel of Figure 9.28) as follows:

Comparison of standard map (left) and continuous area cartogram (right).

FIGURE 9.28: Comparison of standard map (left) and continuous area cartogram (right).

cartogram also offers creation of not-contiguous area cartograms using cartogram_ncont() and Dorling cartograms using cartogram_dorling(). Non-face-to-face area cartograms are created past scaling down each region based on the provided weighting variable. Dorling cartograms consist of circles with their area proportional to the weighting variable. The code clamper below demonstrates cosmos of not-contiguous area and Dorling cartograms of US states' population (Figure nine.29):

Comparison of non-continuous area cartogram (left) and Dorling cartogram (right).

Effigy 9.29: Comparison of non-continuous area cartogram (left) and Dorling cartogram (right).

New mapping packages are emerging all the time. In 2022 alone, a number of mapping packages accept been released on CRAN, including mapdeck, mapsapi, and rayshader. In terms of interactive mapping, leaflet.extras contains many functions for extending the functionality of leaflet (encounter the end of the point-blueprint vignette in the geocompkg website for examples of heatmaps created by leaflet.extras).

Exercises

These exercises rely on a new object, africa. Create it using the world and worldbank_df datasets from the spData parcel as follows (see Affiliate iii):

We will also use zion and nlcd datasets from spDataLarge:

                              zion                =                st_read                (                (                system.file                (                "vector/zion.gpkg", package                =                "spDataLarge"                )                )                )                data                (                nlcd, parcel                =                "spDataLarge"                )                          
  1. Create a map showing the geographic distribution of the Man Evolution Index (HDI) across Africa with base of operations graphics (hint: use plot()) and tmap packages (hint: employ tm_shape(africa) + ...).
    • Name two advantages of each based on the experience.
    • Proper name three other mapping packages and an reward of each.
    • Bonus: create iii more than maps of Africa using these three packages.
  2. Extend the tmap created for the previous practice then the legend has three bins: "Loftier" (HDI to a higher place 0.seven), "Medium" (HDI between 0.55 and 0.7) and "Low" (HDI below 0.55).
    • Bonus: amend the map aesthetics, for case by changing the legend championship, class labels and color palette.
  3. Represent africa's subregions on the map. Change the default color palette and legend title. Side by side, combine this map and the map created in the previous exercise into a single plot.
  4. Create a land cover map of the Zion National Park.
    • Change the default colors to match your perception of the land comprehend categories
    • Add a scale bar and n arrow and change the position of both to improve the map's aesthetic appeal
    • Bonus: Add an inset map of Zion National Park'south location in the context of the Utah state. (Hint: an object representing Utah tin can be subset from the us_states dataset.)
  5. Create facet maps of countries in Eastern Africa:
    • With one facet showing HDI and the other representing population growth (hint: using variables HDI and pop_growth, respectively)
    • With a 'small multiple' per country
  6. Edifice on the previous facet map examples, create animated maps of East Africa:
    • Showing first the spatial distribution of HDI scores and then population growth
    • Showing each country in club
  7. Create an interactive map of Africa:
    • With tmap
    • With mapview
    • With leaflet
    • Bonus: For each approach, add a fable (if not automatically provided) and a calibration bar
  8. Sketch on paper ideas for a spider web mapping app that could be used to make ship or land-employ policies more than evidence based:
    • In the city you live, for a couple of users per twenty-four hour period
    • In the land you alive, for dozens of users per solar day
    • Worldwide for hundreds of users per day and large data serving requirements
  9. Update the code in coffeeApp/app.R so that instead of centering on Brazil the user can select which state to focus on:
    • Using textInput()
    • Using selectInput()
  10. Reproduce Effigy 9.1 and the 1st and 6th panel of Figure ix.6 every bit closely equally possible using the ggplot2 package.
  11. Bring together us_states and us_states_df together and calculate a poverty rate for each state using the new dataset. Next, construct a continuous area cartogram based on total population. Finally, create and compare two maps of the poverty rate: (1) a standard choropleth map and (2) a map using the created cartogram boundaries. What is the information provided by the first and the second map? How do they differ from each other?
  12. Visualize population growth in Africa. Side by side, compare it with the maps of a hexagonal and regular grid created using the geogrid package.

lewhisortates.blogspot.com

Source: https://geocompr.robinlovelace.net/adv-map.html

0 Response to "r plotly draw map in 3d plane"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel