4 Maps

4.1 Integrated maps

los mapas integrados , son mapas mas rapidos donde no se busca los objetos geoespaciales

4.1.1 Overview

Grafico de burbujas usando funcion potly y madbox potly : Plotly es otro paquete de gráficos en R para crear gráficos interactivos con calidad de publicación, se usa para las graficas plot madbox y plox geo.

Sys.setenv('MAPBOX_TOKEN' = 'pk.eyJ1IjoibGloa2lyIiwiYSI6ImNsZnIxNmM2YTAzeTkzc3BvMjRtYWk3cDUifQ.cmuXPv09JIs6GInX5K1uCQ')
library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
plotly::plot_mapbox(maps::canada.cities)     %>%
  plotly::add_markers(
    x = ~long, 
    y = ~lat, 
    size = ~pop, 
    color = ~country.etc,
    colors = "Accent",
    text = ~paste(name, pop),
    hoverinfo = "text"
  )
## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.
## Warning in RColorBrewer::brewer.pal(n, pal): n too large, allowed maximum for palette Accent is 8
## Returning the palette you asked for with that many colors

## Warning in RColorBrewer::brewer.pal(n, pal): n too large, allowed maximum for palette Accent is 8
## Returning the palette you asked for with that many colors

## Warning in RColorBrewer::brewer.pal(n, pal): n too large, allowed maximum for palette Accent is 8
## Returning the palette you asked for with that many colors

## Warning in RColorBrewer::brewer.pal(n, pal): n too large, allowed maximum for palette Accent is 8
## Returning the palette you asked for with that many colors

## Warning in RColorBrewer::brewer.pal(n, pal): n too large, allowed maximum for palette Accent is 8
## Returning the palette you asked for with that many colors

## Warning in RColorBrewer::brewer.pal(n, pal): n too large, allowed maximum for palette Accent is 8
## Returning the palette you asked for with that many colors

## Warning in RColorBrewer::brewer.pal(n, pal): n too large, allowed maximum for palette Accent is 8
## Returning the palette you asked for with that many colors

## Warning in RColorBrewer::brewer.pal(n, pal): n too large, allowed maximum for palette Accent is 8
## Returning the palette you asked for with that many colors

## Warning in RColorBrewer::brewer.pal(n, pal): n too large, allowed maximum for palette Accent is 8
## Returning the palette you asked for with that many colors

## Warning in RColorBrewer::brewer.pal(n, pal): n too large, allowed maximum for palette Accent is 8
## Returning the palette you asked for with that many colors

## Warning in RColorBrewer::brewer.pal(n, pal): n too large, allowed maximum for palette Accent is 8
## Returning the palette you asked for with that many colors

## Warning in RColorBrewer::brewer.pal(n, pal): n too large, allowed maximum for palette Accent is 8
## Returning the palette you asked for with that many colors

## Warning in RColorBrewer::brewer.pal(n, pal): n too large, allowed maximum for palette Accent is 8
## Returning the palette you asked for with that many colors

## Warning in RColorBrewer::brewer.pal(n, pal): n too large, allowed maximum for palette Accent is 8
## Returning the palette you asked for with that many colors

## Warning in RColorBrewer::brewer.pal(n, pal): n too large, allowed maximum for palette Accent is 8
## Returning the palette you asked for with that many colors

## Warning in RColorBrewer::brewer.pal(n, pal): n too large, allowed maximum for palette Accent is 8
## Returning the palette you asked for with that many colors

## Warning in RColorBrewer::brewer.pal(n, pal): n too large, allowed maximum for palette Accent is 8
## Returning the palette you asked for with that many colors

## Warning in RColorBrewer::brewer.pal(n, pal): n too large, allowed maximum for palette Accent is 8
## Returning the palette you asked for with that many colors

## Warning in RColorBrewer::brewer.pal(n, pal): n too large, allowed maximum for palette Accent is 8
## Returning the palette you asked for with that many colors

## Warning in RColorBrewer::brewer.pal(n, pal): n too large, allowed maximum for palette Accent is 8
## Returning the palette you asked for with that many colors

## Warning in RColorBrewer::brewer.pal(n, pal): n too large, allowed maximum for palette Accent is 8
## Returning the palette you asked for with that many colors

## Warning in RColorBrewer::brewer.pal(n, pal): n too large, allowed maximum for palette Accent is 8
## Returning the palette you asked for with that many colors

## Warning in RColorBrewer::brewer.pal(n, pal): n too large, allowed maximum for palette Accent is 8
## Returning the palette you asked for with that many colors

## Warning in RColorBrewer::brewer.pal(n, pal): n too large, allowed maximum for palette Accent is 8
## Returning the palette you asked for with that many colors

## Warning in RColorBrewer::brewer.pal(n, pal): n too large, allowed maximum for palette Accent is 8
## Returning the palette you asked for with that many colors

## Warning in RColorBrewer::brewer.pal(n, pal): n too large, allowed maximum for palette Accent is 8
## Returning the palette you asked for with that many colors

## Warning in RColorBrewer::brewer.pal(n, pal): n too large, allowed maximum for palette Accent is 8
## Returning the palette you asked for with that many colors

## Warning in RColorBrewer::brewer.pal(n, pal): n too large, allowed maximum for palette Accent is 8
## Returning the palette you asked for with that many colors

Figura 4.1

Grafico de burbujas usando la opcion de mapeo integrado de potly,js madbox y plotgeo que crean un mapa dinamico de unos datos especificos , tambien se sabe que son capas basadas en dispersion .

Plotly ,es otro paquete de gráficos en R para crear gráficos interactivos con calidad de publicación, se usa para las graficas plot madbox y plox geo.

library(plotly)
## Loading required package: ggplot2
## 
## Attaching package: 'plotly'
## The following object is masked from 'package:ggplot2':
## 
##     last_plot
## The following object is masked from 'package:stats':
## 
##     filter
## The following object is masked from 'package:graphics':
## 
##     layout
library(listviewer)

styles <- schema()$layout$layoutAttributes$mapbox$style$values
styles
##  [1] "basic"             "streets"           "outdoors"         
##  [4] "light"             "dark"              "satellite"        
##  [7] "satellite-streets" "carto-darkmatter"  "carto-positron"   
## [10] "open-street-map"   "stamen-terrain"    "stamen-toner"     
## [13] "stamen-watercolor" "white-bg"
#>  [1] "basic"             "streets"          
#>  [3] "outdoors"          "light"            
#>  [5] "dark"              "satellite"        
#>  [7] "satellite-streets" "open-street-map"  
#>  [9] "white-bg"          "carto-positron"   
#> [11] "carto-darkmatter"  "stamen-terrain"   
#> [13] "stamen-toner"      "stamen-watercolor"
layout(
  plot_mapbox(), 
  mapbox = list(style = "satellite")
)
## No scattermapbox mode specifed:
##   Setting the mode to markers
##   Read more about this attribute -> https://plotly.com/r/reference/#scatter-mode

Figura 4.2

El mapa base de Mapbox se controla a través del layout.mapbox.styleatributo y este se muestra en forma de satelite , donde se ve cada lugar del planeta tierra por medio de este . plot mapbox nos sirvio para buscar una informacion requerida para crear los mapas.

style_buttons <- lapply(styles, function(s) {
  list(
    label = s, 
    method = "relayout", 
    args = list("mapbox.style", s)
  )
})
layout(
  plot_mapbox(), 
  mapbox = list(style = "dark"),
  updatemenus = list(
    list(y = 0.8, buttons = style_buttons)
  )
)
## No scattermapbox mode specifed:
##   Setting the mode to markers
##   Read more about this attribute -> https://plotly.com/r/reference/#scatter-mode

Figura 4.3

Muestra menus con los cuales te muestra de manera rapida pero , calles , satelite , pueblos etc cada botón utiliza el método de retransmisión para modificar el atributo layout.mapbox.style y cambiar el estilo del mapa base.

library(plotly)
library(dplyr)
# airport locations
air <- read.csv(
  'https://plotly-r.com/data-raw/airport_locations.csv'
)
# flights between airports
flights <- read.csv(
  'https://plotly-r.com/data-raw/flight_paths.csv'
)
flights$id <- seq_len(nrow(flights))

# map projection
geo <- list(
  projection = list(
    type = 'orthographic',
    rotation = list(lon = -100, lat = 40, roll = 0)
  ),
  showland = TRUE,
  landcolor = toRGB("gray95"),
  countrycolor = toRGB("gray80")
)

plot_geo(color = I("red")) %>%
  add_markers(
    data = air, x = ~long, y = ~lat, text = ~airport,
    size = ~cnt, hoverinfo = "text", alpha = 0.5
  ) %>%
  add_segments(
    data = group_by(flights, id),
    x = ~start_lon, xend = ~end_lon,
    y = ~start_lat, yend = ~end_lat,
    alpha = 0.3, size = I(1), hoverinfo = "none"
  ) %>%
  layout(geo = geo, showlegend = FALSE)
## Warning: `line.width` does not currently support multiple values.

Figura 4.4

Para visualizar rutas de vuelo dentro de los Estados Unidos usando plot geo para proyectar las geometrias

map1 <- plot_mapbox() %>% 
  add_segments(x = -100, xend = -50, y = 50, yend = 75) %>%
  layout(
    mapbox = list(
      zoom = 0,
      center = list(lat = 65, lon = -75)
    )
  )

map2 <- plot_geo() %>% 
  add_segments(x = -100, xend = -50, y = 50, yend = 75) %>%
  layout(geo = list(projection = list(type = "mercator")))

library(htmltools)
browsable(tagList(map1, map2))

Figura 4.5

Se usan las diferentes funciones para mad plox es recto y para geo es curvo, muestra el sistema de coordenadas de un plano no cartesiano.

4.1.2 Choropleths

library(plotly)
density <- state.x77[, "Population"] / state.x77[, "Area"]

g <- list(
  scope = 'usa',
  projection = list(type = 'albers usa'),
  lakecolor = 'white'
)

plot_geo() %>%
  plotly::add_trace(
    z = ~density, text = state.name, span = I(0),
    locations = state.abb, locationmode = 'USA-states'
  ) %>%
  layout(geo = g)

Figura 4.6

  1. Los mapas de coropletas son aquellos que utilizan colores o tramas para representar cualquier fenómeno sobre un mapa dividido en unidades de superficie (comarcas, provincias, CC.AA, países…)., en este perimero se muestra la densidad de la poblacion de los estados unidos menor densidad son los datos morados y los de mayor los amarillos.
plot_ly() %>%
  add_trace(
    type = "choroplethmapbox",
    # See how this GeoJSON URL was generated at
    # https://plotly-r.com/data-raw/us-states.R
    geojson = paste(c(
      "https://gist.githubusercontent.com/cpsievert/",
      "7cdcb444fb2670bd2767d349379ae886/raw/",
      "cf5631bfd2e385891bb0a9788a179d7f023bf6c8/", 
      "us-states.json"
    ), collapse = ""),
    locations = row.names(state.x77),
    z = state.x77[, "Population"] / state.x77[, "Area"],
    span = I(0)
  ) %>%
  layout(
    mapbox = list(
      style = "light",
      zoom = 4,
      center = list(lon = -98.58, lat = 39.82)
    )
  ) %>%
  config(
    mapboxAccessToken = Sys.getenv("MAPBOX_TOKEN"),
    # Workaround to make sure image download uses full container
    # size https://github.com/plotly/plotly.js/pull/3746
    toImageButtonOptions = list(
      format = "svg", 
      width = NULL, 
      height = NULL
    )
  )

Figura 4.7

choroplethmapbox paquete geoson que permite la geometria del mapa donde vemos la densidad representada en diferentes colores , tambien se ve la geometria y sus colores incluyendo el nombre de los estados .

4.2 Custom maps

4.2.1 Simple features (sf)

library(rnaturalearth)
world <- ne_countries(returnclass = "sf")
class(world)
## [1] "sf"         "data.frame"
#> [1] "sf"    "data.frame"
plotly::plot_ly(world, color = I("gray90"), stroke = I("black"), span = I(1))
## No trace type specified:
##   Based on info supplied, a 'scatter' trace seems appropriate.
##   Read more about this trace type -> https://plotly.com/r/reference/#scatter

Figura 4.8

muestra el mapa mundi completo con sus limites , libreria sf , La idea clave detrás de sf es que almacena geometrías geoespaciales en una columna de lista de un marco de datos.

library(rnaturalearth)
canada <- ne_states(country = "Canada", returnclass = "sf")
plotly::plot_ly(canada, split = ~name, color = ~provnum_ne)
## No trace type specified:
##   Based on info supplied, a 'scatter' trace seems appropriate.
##   Read more about this trace type -> https://plotly.com/r/reference/#scatter

Figura 4.9

Divide las provincias de canada por colores y su numero

plotly::plot_ly(
  canada, 
  split = ~name, 
  color = I("gray"), 
  text = ~paste(name, "is \n province number", provnum_ne),
  hoveron = "fills",
  hoverinfo = "text",
  showlegend = FALSE
)
## No trace type specified:
##   Based on info supplied, a 'scatter' trace seems appropriate.
##   Read more about this trace type -> https://plotly.com/r/reference/#scatter

Figura 4.10

En esta grafica hacen uso de diferentes funciones como split , que muestra el desplazamiento de cada poligono con sus rellenos , la otra funcion es text que brinda informacion sobre dicho lugar funciones para mostrar información sobre herramientas

base <- map_data("world", "canada") %>%
  group_by(group) %>%
  plotly_empty(x = ~long, y = ~lat, alpha = 0.2) %>%
  layout(showlegend = FALSE, xaxis = list(scaleanchor = "y"))
  
base %>%
  add_polygons(hoverinfo = "none", color = I("black")) %>%
  add_markers(text = ~paste(name, "<br />", pop), hoverinfo = "text", 
              color = I("red"), data = maps::canada.cities)

Figura 4.12

La población de varias ciudades canadienses representada en un mapa base sp es un paquete que nos proporciona clases y métodos para tratar con datos espaciales, por ejemplo crear mapas a partir de datos y aca hablamos de la poblacion

Referencias Chamberlain, Scott y Andy Teucher. 2018. Geojsonio: convertir datos desde y hacia ‘Geojson’ o ‘Topojson’ . https://CRAN.R-project.org/package=geojsonio .

Dorling, D. 1996. “Cartogramas de área: su uso y creación”. Conceptos y Técnicas en Geografía Moderna (CATMOG) .

Hijmans, Robert J. 2019. Ráster: análisis y modelado de datos geográficos . https://CRAN.R-project.org/package=raster .

James A. Dougenik, Nicholas R. Chrisman, Duane R. Niemeyer. 1985. “Un algoritmo para construir cartogramas de área continua”. El geógrafo profesional .

Jeworutzki, Sebastián. 2018. Cartograma: Crear Cartogramas con R . https://CRAN.R-project.org/package=cartograma .

Mullen, Lincoln A. y Jordan Bratt. 2018. “Usaboundaries: Límites históricos y contemporáneos de los Estados Unidos de América”. Revista de software de código abierto 3 (23): 314. https://doi.org/10.21105/joss.00314 .

Newmann, Mark. 2016. “Mapas de los resultados de las elecciones presidenciales estadounidenses de 2016”. Blog. http://www-personal.umich.edu/~mejn/election/2016/ .

Nusrat S, Alam MJ, Kobourov S. 2018. “Evaluación de la efectividad del cartograma”. Gráfico de cálculo transvis IEEE . https://doi.org/10.1109/TVCG.2016.2642109 .

Olson, JM 1976. “Cartogramas de áreas no contiguas”. El geógrafo profesional .

Pebesma, Edzer. 2018. Sf: Funciones simples para R . https://CRAN.R-project.org/package=sf .

Pebesma, Edzer J. y Roger S. Bivand. 2005. “Clases y métodos para datos espaciales en R”. Noticias R 5 (2): 9–13. https://CRAN.R-project.org/doc/Rnews/ .

Colaboradores de PROJ. 2018. Biblioteca de software de transformación de coordenadas PROJ . Fundación Geoespacial de Código Abierto. https://proj4.org/ .

Equipo central R. 2016. R: un lenguaje y un entorno para la computación estadística . Viena, Austria: Fundación R para la Informática Estadística. https://www.R-project.org/ .

Robin Lovelace, Jannes Muenchow, Jakub Nowosad. 2019. Geocomputación con R . Chapman y Hall/CRC.

Sievert, Carson. 2018b. “Aprender y mejorar las conversiones de Ggplotly”. Blog. https://blog.cpsievert.me/2018/01/30/learning-improving-ggplotly-geom-sf/ .

Sur, Andy. 2017. Rnaturalearth: datos del mapa mundial de Natural Earth . https://CRAN.R-project.org/package=rnaturalearth .

Wickham, Hadley. 2014b. “Datos ordenados”. La Revista de Software Estadístico 59 (10). http://www.jstatsoft.org/v59/i10/ .