R has some excellent mapping options. there is the R newsletter package., which I use when I want to do a lot of customization. There is tmapI love it for its nice balance of power and ease of use. I have recently started using View Map.

The reason mapview exists is for heuristic visualization – more specifically, the creation of useful virtual maps with very little code. small code like:

mapview(mydata, zcol = "mycolumn")

One job, two arguments, done. This makes it extremely easy to explore geospatial data, or create a quick prototype. Plus mapview has some great syntax options for displaying multiple maps.

Mapview at work

For this demonstration, I will be using a file of US state figures and data on population changes by state in the past 20 years. If you want to continue, download the zip data file:

Loading

State and state capital data for use with InfoWorld’s MapView tutorial Sharon Machlis

As usual, first a little data preparation. The code below loads four packages, downloads a GIS file that defines state polygon boundaries, and then joins that with state residents in 2000, 2010 and 2020.

library(tigris)
library(mapview)
library(dplyr)
library(sf)
us_geo <- tigris::states(cb = TRUE, resolution = '20m')
pop_data <- readr::read_csv("state_population_data.csv")
all_data <- inner_join(us_geo, pop_data, by = c("GEOID" = "GEOID")) 

With my data ready, this single line of code is all I need to create an interactive map to explore my data, colored by percentage change between 2010 and 2020:

mapview(all_data, zcol = "PctChange10_20")

A screenshot of the default map is shown below, including a popup table that appears if you click on a case and hover text that appears on hover/mouse over a state.

Map of the 48 contiguous US states colored by demographic change with a pop-up spreadsheet Screenshot of Sharon Machlis

The default mapview is created with one small line of code.

Note what is Not in the code that generated this map. I didn’t have to specify in any way that I’m parsing polygons or that I want a polygon color map; mapview() Choose defaults based on the type of geospatial file. code mapview(all_data, zcol = "PctChange10_20") It is everything you need to create an interactive corrective map – including scrolling text and popups.

The default popup includes every field in my data, and that probably isn’t what I want the end user to see. However, it is useful to explore my data. And the popup is customizable, which I’ll get to shortly.

If your dataset does not contain row names, mapview() The row number is used for the top row of the popup table. You can add row names to your dataset with base R. row.names() Function to get more table titles easy to use.

By the way, if your table’s format isn’t as good as the one in this map, try updating GDAL on your system. I have updated a file rgdal حزمة package on my system and the table format issue was resolved.

More Map View Features

If you look very carefully at the top left of the map in the screenshot above, you’ll see some text showing the longitude and latitude of the mouse’s location at the time the image was taken, as well as the zoom level of the published map. Both change when you interact with the map.

This virtual map also includes a scale in kilometers and miles at the bottom left. And at the bottom right, there is a button with the name of the data set and column. If you pan, zoom in or out on the mapAnd Clicking this button will take you back to the starting point of the map.

Visualize points using Mapview

Adding points to a map is just as easy as polygons. For points, I’ll be using a CSV file of the state capitals with their latitude and longitude.

In the code below I am using the rio package to read the csv file, but you can use another option like readr::read_csv(). To use the latitude and longitude data for GIS work in R (not just for map rendering), you then need to convert the data frame to my place opposed. sf . package st_as_sf() function do this.

capitals <- rio::import("us-state-capitals.csv")
capitals_geo <- st_as_sf(capitals, coords = c("longitude", "latitude"),
crs = 4326)

st_as_sf() It needs the data frame as arguments, and a vector specifying the columns containing the latitude and longitude information, and the required coordinate system reference, in which case a lot of background map boxes use it.

Once the data is transformed, I can use it to add a point layer to my map with another call to mapview():

mapview(all_data, zcol="PctChange10_20") + 
mapview(capitals_geo)

I didn’t have to tell Mapview that capitals_geo Contains points, or columns that contain latitude and longitude data. In fact, once I create my first Mapview object, I can add layers to the map without calling mapview() repeatedly; I can just use the name of the dot object:

mapview(all_data, zcol = "PctChange10_20") + capitals_geo

The map now looks like this:

A map showing the US states and departments in the location of the capital of each state Screenshot of Sharon Machlis

Map with polygons and points.

Automatic visual recall

You can also ask mapview to automatically visualize geospatial objects in the R session. Package startWatching() The function creates a map of any sf object you add or change in an R session after the function has been called. You can see how it works in the embedded video at the top of this article.

Customizing R Maps with Mapview

over there mapview() Media to customize map options such as color for polygon boundary linesAnd col.regions to fill the polygon Colors, And alpha.regions for transparency.

You can rename a layer with the extension layer.name An argument if you want a more user-friendly layer name. This appears in the legend, the bottom right button, and when you open the layer button toward the top left.

In the following code block, I changed the polygon colors and opacity using the “Greens” panel from the RColorBrewer package and opacity 1 so that the polygons are opaque. (Note that you will need to install the RColorBrewer package if you want this code to run on your system.)

 mapview(all_data, zcol = "PctChange10_20", 
col.regions = RColorBrewer::brewer.pal(9, "Greens"),
alpha.regions = 1)

The Greens palette contains a maximum of nine separate colors. Mapview complains if you don’t give it a palette with the number of colors it needs, as shown in the warning below, but it will do the interpolation for you.

Warning message: 
Found less unique colors (9) than unique zcol values (41)!
Interpolating color vector to match number of zcol values.

You can also use a contrast panel in your map, like the RdYlGn panel:

mapview(all_data, zcol = "PctChange10_20", 
col.regions = RColorBrewer::brewer.pal(11, "RdYlGn"), alpha.regions = 1)
Map of US states by population change colored green, yellow, and red with a black background Screenshot of Sharon Machlis

The dark background for this map appeared automatically, because Mapview determined that the map included too many light colors. You can turn off basemap behavior with

Imagine two maps together

Now onto a couple of great syntax options I mentioned at the beginning. Here I am creating two maps, one for population change from 2010 to 2020 and one for 2000 to 2010:

map2020 <- mapview(all_data, zcol = "PctChange10_20", 
col.regions = RColorBrewer::brewer.pal(9, "Greens"), alpha.regions = 1,
layer.name = "Pct change 2010-2020"
)
map2010 <- mapview(all_data, zcol = "PctChange00_10",
col.regions = RColorBrewer::brewer.pal(9, "Greens"), alpha.regions = 1,
layer.name = "Pct change 2000-2010"
)

You can put maps side by side and have them move in sync with the Leafsync package and sync() Job.

library(leafsync)
sync(map2010, map2020)
Two maps of the United States side by side Screenshot of Sharon Machlis

These two maps zoom in, zoom out and pan together.

Or you can put two maps on the same layer and have a side-by-side slider to compare the two, thanks to the prism package. | (Unix tube, not R tube).

map2010 | map2020
The map with the slider in the middle that slides back and forth to show the right or left version. Screenshot of Sharon Machlis

The map slider can be moved from left to right to show the left or right version of the map.

Don’t want legends, popups, or text hovering over the map? This can be stopped with

mapview(all_data, zcol = "PctChange10_20", 
        legend = FALSE, label = FALSE, popup = FALSE)

You can also turn off background map tiles using custom dataset projection. One case where this is useful is if you want a map of the United States that shows Alaska and Hawaii as two entries, rather than where they are actually geographically located, for a more compact display.

The first four lines of code below use the ALPERSASA package to create a GIS file with Alaska and Hawaii as entries. But the default map rendering generated from this data still showed default background boxes, resulting in Alaska and Hawaii superimposed on Mexico.

library(albersusa)
us_geo50 <- usa_sf("lcc") %>% mutate(GEOID = as.character(fips_state))
pop_data50 <- readr::read_csv("data/state_population_data50.csv")
all_data50 <- inner_join(us_geo50, pop_data50, by = c("GEOID" = "GEOID"))
mapview(all_data50, zcol = "PctChange10_20")
A map of the United States has Alaska and Hawaii as entries, but it appears on a map of Mexico Screenshot of Sharon Machlis

Sometimes you may want to use a custom drop and remove background map boxes.

If you ask Mapview to use the original projection of the data, the projection is accurate and the background no longer includes map boxes.

mapview(all_data50, zcol = "PctChange10_20", 
native.crs = TRUE)
Map of the United States with Alaska and Hawaii as inputs and no map tiles in the background. Screenshot of Sharon Machlis

Using custom projection could allow for more flexible screens, such as this US map with Alaska and Hawaii as indoor groups.

More customizations for R mapview

You can customize trash breakpoints with the extension at Controversy. In the code below, I set commas using base R. seq() A function, from -4 to 20 in increments of 2. The map and key colors will show new separators.

mapview(all_data, zcol = "PctChange10_20", 
at = seq(-4, 20, 2))

You can customize the popup and text hover using the same techniques as in the R newsletter package. I’m sure there are several ways to do this, but this is my usual process:

First, create a vector of strings – using HTML code if you want to format – using a file dataframe$column_name Syntax for variables. I find the glue pack useful for this, although you can paste() like that. For example:

mylabel <- glue::glue("{all_data$State} {all_data$PctChange10_20}%")

Second, apply htmltools packages HTML() Operate to the vector with lapply() So you end up with a list – because you need a list – like:

mypopup <- glue::glue("<strong>{all_data$State}</strong><br />
Change 2000-2010: {all_data$PctChange00_10}%<br />
Change 2010-2020: {all_data$PctChange10_20}%") %>%
lapply(htmltools::HTML)
mylabel <- glue::glue("{all_data$State} {all_data$PctChange10_20}%") %>%
lapply(htmltools::HTML)

My popup now looks like this:

head(mypopup, 3) 
[[1]] <strong>Washington</strong><br />
Change 2000-2010: 14.1%<br />
Change 2010-2020: 14.6%
[[2]] <strong>Puerto Rico</strong><br />
Change 2000-2010: -2.2%<br />
Change 2010-2020: -11.8%
[[3]] <strong>South Dakota</strong><br />
Change 2000-2010: 7.9%<br />
Change 2010-2020: 8.9%

Source link

Leave a Reply

Your email address will not be published.