• Artículos
  • Documentos
    • Libro de Energía Solar Fotovoltaica
  • Omnia sunt Communia!

Omnia sunt Communia!

~ Sobre software, documentación y ciencia libres

Omnia sunt Communia!

Archivos de etiqueta: raster

R para Datos Espaciales

23 domingo Nov 2014

Posted by Oscar Perpiñán Lamigueiro in R-castellano

≈ Comentarios desactivados en R para Datos Espaciales

Etiquetas

datos espaciales, geoestadística, R, raster, UPM, visualización

Durante este mes de Noviembre he tenido la oportunidad de impartir un curso introductorio de R en el CEIGRAM de la UPM. He utilizado el material que está disponible aquí, que he corregido y mejorado.

Algunos participantes tenían especial interés en conocer las posibilidades que ofrece R para trabajar con datos espaciales. Esta es la información que les he hecho llegar.

La primera fuente de información es la CRAN Tasks View «Analysis of Spatial Data’’ . Hace un resumen exhaustivo de todos los paquetes que sirven para leer y escribir, visualizar, y analizar datos espaciales. También es útil la web http://rspatial.r-forge.r-project.org/, aunque es algo antigua. Por otra parte, existe un libro de referencia, “Applied Spatial Data Analysis with R”, de Bivand, Pebesma y Gómez-Rubio. Todo el código está disponible en su web.

Dentro de los paquetes destacan:

  • sp  es el paquete fundamental para trabajar con datos vectoriales (puntos, líneas y polígonos). Es de los mismos autores que el libro que mencionaba. Es recomendable leer este documento introductorio.
  • raster es el paquete fundamental para trabajar con datos raster (matrices georeferenciadas, típicas en imágenes de satélite y similares). Define funciones para crear, leer, manipular y escribir este tipo de datos. Es recomendable leer este documento introductorio.
  • gstat es el paquete por excelencia para hacer análisis geoestadístico en R. Permite hacer modelado de variogramas, interpolación IDW, kriging ordinario, y kriging con regresión. Se estudia en profundidad en el libro que indicaba antes. Es recomendable este documento de introducción.
  • rgdal es una interface para GDAL. Entre otras cosas, permite transformar proyecciones. Complementa a sp y raster.
  • maptools proporciona funciones para leer y manipular datos tipo “shapefile”. Es un buen complemento para sp.

En cuanto a fuentes de datos tipo espaciales destacaría las siguientes:

  • NASA Earth Observations (NEO). En este repositorio de imágenes hay que seleccionar el formato GeoTiff para poder usarlo con el paquete raster.
  • Natural Earth Data.
  • DIVA-GIS.
  • CM SAF.  Sobre esta fuente publicamos un artículo hace algo más de un año. El código asociado está disponible en este repositorio. Es un recurso útil para ver cómo usar datos raster y vectoriales en R, y cómo usar las funciones de gstat para hacer variogramas y kriging.
  • En esta wiki recopilo fuentes de datos meteorológicos.

Por último, para la visualización de datos espaciales, pueden resultar útil dos recursos que he publicado:

  • El paquete rasterVis, que complementa al paquete raster, para visualización de datos raster. En su web hay varios ejemplos de uso, y hay unos tutoriales publicados por Agustín Lobo.
  • El libro que publiqué hace unos meses, “Displaying Time Series, Spatial, and Space-Time Data with R”. El código y las imágenes principales están disponibles en su web.
Anuncio publicitario

Comparte / Share

  • Correo electrónico
  • Imprimir
  • Twitter
  • Facebook
  • LinkedIn
  • Pinterest
  • Más
  • Tumblr
  • Reddit

Me gusta esto:

Me gusta Cargando...

meteoForecast, a package to obtain NWP-WRF forecasts in R

08 martes Jul 2014

Posted by Oscar Perpiñán Lamigueiro in R-english, Software

≈ 13 comentarios

Etiquetas

forecast, NWP, R, raster, spatial, WRF

wrfDaysThe Weather Research and Forecasting (WRF) Model is a numerical weather prediction (NWP) system. NWP refers to the simulation and prediction of the atmosphere with a computer model, and WRF is a set of software for this.

meteoForecast is a new R package that implements functions to download data from the Meteogalicia and OpenMeteo NWP-WRF services using the NetCDF Subset Service.

Read this introduction for additional information and examples.

Comparte / Share

  • Correo electrónico
  • Imprimir
  • Twitter
  • Facebook
  • LinkedIn
  • Pinterest
  • Más
  • Tumblr
  • Reddit

Me gusta esto:

Me gusta Cargando...

rasterVis tutorials

13 martes May 2014

Posted by Oscar Perpiñán Lamigueiro in R-english, visualization

≈ 1 comentario

Etiquetas

GoogleMaps, raster, raster layers, rasterVis, spatial data, visualization

Agustin Lobo has recently published some good tutorials about rasterVis:

  • Introduction to rasterVis
  • Overlay your raster layer on a backround GoogleMaps layer
  • Overlay vectors on raster layers
  • Vectorplot

rastervisBTC

Regarding the second tutorial, there has been an interesting discussion in the R-sig-Geo mailing list about the projection of the ggmap output.

Comparte / Share

  • Correo electrónico
  • Imprimir
  • Twitter
  • Facebook
  • LinkedIn
  • Pinterest
  • Más
  • Tumblr
  • Reddit

Me gusta esto:

Me gusta Cargando...

Maps with R (II)

20 lunes Feb 2012

Posted by Oscar Perpiñán Lamigueiro in R-english, visualization

≈ 7 comentarios

Etiquetas

GeoTIFF, land cover, lattice, population, R, raster, rasterVis

In my my last post I described how to produce a multivariate choropleth map with R. Now I will show how to create a map from raster files. One of them is a factor which will group the values of the other one. Thus, once again, I will superpose several groups in the same map.

NOTE: Although the procedure described in this post is valid, there is a newer code version in one of the chapters of the book «Displaying time series, spatial and space-time data with R«

First let’s load the packages.

library(raster)
library(rasterVis)
library(colorspace)

Now, I define the geographical extent to be analyzed (approximately India and China).

ext <- extent(65, 135, 5, 55)

The first raster file is the population density in our planet, available at this NEO-NASA webpage (choose the Geo-TIFF floating option, ~25Mb). After reading the data with raster I subset the geographical extent and replace the 99999 with NA.

pop <- raster('875430rgb-167772161.0.FLOAT.TIFF')
pop <- crop(pop, ext)
pop[pop==99999] <- NA
pTotal <- levelplot(pop, zscaleLog=10, par.settings=BTCTheme)
pTotal

The second raster file is the land cover classification (available at this NEO-NASA webpage)

landClass <- raster('241243rgb-167772161.0.TIFF')
landClass <- crop(landClass, ext)

The codes of the classification are described here. In summary, the sea is labeled with 0, forests with 1 to 5, shrublands, grasslands and wetlands with 6 to 11, agriculture and urban lands with 12 to 14, and snow and barren with 15 and 16. This four groups (sea is replaced NA) will be the levels of the factor. (I am not sure if these sets of different land covers is sensible: comments from experts are welcome!)

EDIT: Following a question from a user of rasterVis I include some lines of code to display this qualitative variable in the map.
EDIT2: raster and rasterVis are able to work with categorical data using ratify.

  landClass[landClass %in% c(0, 254)] <- NA
  landClass <- cut(landClass, c(0, 5, 11, 14, 16))
  ## Add a Raster Atribute Table and define the raster as categorical data
  landClass <- ratify(landClass)
  ## Configure the RAT: first create a RAT data.frame using the
  ## levels method; second, set the values for each class (to be
  ## used by levelplot); third, assign this RAT to the raster
  ## using again levels
  rat <- levels(landClass)[[1]]
  rat$classes <- c('Forest', 'Land', 'Urban', 'Snow')
  levels(landClass) <- rat

  levelplot(landClass, col.regions=terrain_hcl(4))

This histogram shows the distribution of the population density in each land class.

s <- stack(pop, landClass)
layerNames(s) <- c('pop', 'landClass')
histogram(~log10(pop)|landClass, data=s,
            scales=list(relation='free'))

Everything is ready for the map. I will create a list of trellis objects with four elements (one for each level of the factor). Each of these objects is the representation of the population density in a particular land class. I use the same scale for all of them to allow for comparisons (the at argument of levelplot receives the correspondent at values from the global map)

at <- pTotal$legend$bottom$args$key$at

pList <- lapply(1:nClasses, function(i){
  landSub <- landClass
  landSub[!(landClass==i)] <- NA
  popSub <- mask(pop, landSub)
  step <- 360/nClasses
  pal <- rev(sequential_hcl(16, h = (30 + step*(i-1))%%360))
  pClass <- levelplot(popSub, zscaleLog=10, at=at,
                      col.regions=pal, margin=FALSE)
})

And that’s all. The rest of the code is exactly the same as in the previous post. If you execute it you will get this image (click on it for higher resolution).

Related articles
  • Maps with R (I)
  • Maps with R (III)
  • Spatial data visualization with R
  • Stamen maps with spplot

https://github.com/oscarperpinan/spacetime-vis/tree/master/code/raster.R

Comparte / Share

  • Correo electrónico
  • Imprimir
  • Twitter
  • Facebook
  • LinkedIn
  • Pinterest
  • Más
  • Tumblr
  • Reddit

Me gusta esto:

Me gusta Cargando...

rasterVis

06 miércoles Jul 2011

Posted by Oscar Perpiñán Lamigueiro in R-english, visualization

≈ 10 comentarios

Etiquetas

CRAN, lattice, levelplot, raster, visualization

The raster package defines classes and methods for spatial raster data access and manipulation. The new rasterVis package complements raster providing a set of methods for enhanced visualization and interaction. It is now at CRAN.

Several examples can be found at the webpage of the project.

https://procomun.files.wordpress.com/2011/06/wpid-levelplot_layer11.png

Comparte / Share

  • Correo electrónico
  • Imprimir
  • Twitter
  • Facebook
  • LinkedIn
  • Pinterest
  • Más
  • Tumblr
  • Reddit

Me gusta esto:

Me gusta Cargando...
← Entradas anteriores

Omnia sunt communia!

“As we enjoy great advantages from the inventions of others, we should be glad of an opportunity to serve others by any invention of ours, and this we should do freely and generously”

RSS Feed RSS - Entradas

Introduce tu correo electrónico para suscribirte a este blog y recibir avisos de nuevas entradas.

Únete a otros 91 suscriptores

Posts Más Vistos

  • Libro de Energía Solar Fotovoltaica
  • Vector fields with streamlines
View Oscar Perpiñán Lamigueiro's profile on LinkedIn
profile for Oscar Perpiñán on Stack Exchange, a network of free, community-driven Q&A sites
Citations for Oscar Perpinan

@oscarperpinan

Mis tuits

Enlaces

  • Displaying time series, spatial and space-time data with R
  • Introducción a R

Top Clicks

  • oscarperpinan.github.com/…
  • r-bloggers.com/2023/05/3d…

Etiquetas

actuar anarquía autocontención ayuda mutua bloch ciencia circuitos eléctricos común cooperación CRAN creative commons data data.table data analysis ecología emacs Energía energía solar fotovoltaica entropía EOI esperanza exergía forecast fotovoltaica galeano github GNU General Public License información investigación jorge riechmann kropotkin latex lattice lewis mumford libro lyx map maps memoir meteorological data movimientos sociales nestoria nicolas georgescu roegen NWP open data openstreetmap orgmode pensar photovoltaics pobreza R R-project radiación solar raster rasterVis reproducible research siar small multiples software libre solar solar radiation sp spatial spatial data spplot tecnología time series trellis tufte uned utopía Vector field visualización visualization WRF

RSS R-bloggers

  • Simulating confounders, colliders and mediators by @ellis2013nz
  • Introduction to Mixed-effects Models in R workshop
  • Learn to ‘Make an outstanding Shiny App’ with us
  • Sorting, Ordering, and Ranking: Unraveling R’s Powerful Functions
  • Galton and Watson voluntarily skipping some generations
  • {attachment} v0.4.0: Breaking changes and configuration file for a better experience
  • Sharing the Big Book of R upgrade proposal
  • The do.call() function in R: Unlocking Efficiency and Flexibility
  • Version 1.0.0 of NIMBLE released, providing automatic differentiation, Laplace approximation, and HMC sampling
  • Checking normality in R

RSS dataanalytics

  • Se ha producido un error; es probable que la fuente esté fuera de servicio. Vuelve a intentarlo más tarde.

RSS Solar Energy (Elsevier)

  • Se ha producido un error; es probable que la fuente esté fuera de servicio. Vuelve a intentarlo más tarde.

RSS Progress in Photovoltaics

  • Se ha producido un error; es probable que la fuente esté fuera de servicio. Vuelve a intentarlo más tarde.

RSS Madridmasd

  • Cambio Climático, Gobiernos y Empresas; Casi todas sus promesas son mentira
  • Proyectos estratégicos para la recuperación y transformación económica (PERTE)
  • ¿En quién confiar? Debate sobre IA, ética y comunicación en el congreso de medios de comunicación
  • La Civilización perdida bajo los suelos y vegetación de Latinoamérica.
  • IMDEA Software e IMDEA Networks trabajan para desplegar en la Comunidad de Madrid “MadQCI”: la mayor red cuántica de Europa
  • Etnografía y Paleoecología de los Paisajes Precolombinos: El Papel del Fuego en las Culturas Aborígenes del SO de América del Norte (tribus Karuk y Yurok)
  • Homenaje a Manuel Espadas Burgos
  • Super Mario World
  • Taller doctoral en Historia de las Relaciones Internacionales 2023 en la Universidad de Padua
  • Directiva Europea de Protección de Suelos: Dos décadas de “vistas” y “consideraciones” y otras desconsideraciones
Licencia Creative Commons
Salvo indicación en contra todos los contenidos están publicados por Oscar Perpiñán Lamigueiro bajo una Licencia Creative Commons Reconocimiento-No Comercial-Compartir Igual 3.0 Unported.

Crea un blog o un sitio web gratuitos con WordPress.com.

Privacidad y cookies: este sitio utiliza cookies. Al continuar utilizando esta web, aceptas su uso.
Para obtener más información, incluido cómo controlar las cookies, consulta aquí: Política de cookies
  • Seguir Siguiendo
    • Omnia sunt Communia!
    • Únete a 91 seguidores más
    • ¿Ya tienes una cuenta de WordPress.com? Inicia sesión.
    • Omnia sunt Communia!
    • Personalizar
    • Seguir Siguiendo
    • Regístrate
    • Iniciar sesión
    • Denunciar este contenido
    • Ver sitio web en el Lector
    • Gestionar las suscripciones
    • Contraer esta barra
 

Cargando comentarios...
 

    A %d blogueros les gusta esto: