temperature maps in R

Hello guys,

Please, I need help with generating temperature maps in R. I have a grided temperature data for a region in West Africa and want to draw a temperature map for the region alone without showing the outlying areas. Any thought on how to do this

There are several packages that support maps and spatial analysis in R.

The sf package can do all the things you've listed, and offers package-vignettes to help you use the tool.

And of course, setting up your issue with a reproducible example is a great way to seek help here.
(FAQ: What's a reproducible example (`reprex`) and how do I create one?)

This will depend on format of your data. Gridded measurements like temperature you describe, or remote sensing (satellite) data are often approached via the package raster.

Rasters are easily clipped via raster::mask().

Or you can use general vector maps - sf is currently the best practice, but you will encounter the older package sp a lot in older online materials; it may be obsolete now, but it lived a long and happy life.

Intersection of a grid and a sf object representing boundaries is done via sf::st_intersection().

For an example of a clipped grid created via sf workflow consider this Stack Overflow answer: https://stackoverflow.com/questions/53789313/creating-an-equal-distance-spatial-grid-in-r/53801517#53801517

You would of course need to link the grid to your data and use your favorite plotting library (I suggest ggplot2, but I am not a prude) to draw the map.

1 Like

Hi EconomiCurtis,

Thanks for the prompt response and suggestion for the reprex. Tried it and I hope what I did was the right the thing (concerning the reprex).

So I have temperature data for West Africa and managed to extract the portion for Ghana using grid-specific location for Ghana thus producing the longitudes, latitudes and temperature recorded in that region from 1980 to 2010. Now, I want to create map for this region with the shape of Ghana displayed. Tried merging Ghana shapefiles and the data frame I generated from the grid location to create the map but I received error messages. Unfortunately, I did not record that error message in this reprex. But below is what I've done so far. Please let me know if my reprex worked. Also, I tried the sf package but it does not install in my RStudio

#> 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

Created on 2019-06-12 by the reprex package (v0.2.1)

Hello jlacko,

the temperature data was extracted from a netcdf file for the location I needed, which in this case is Ghana. the whole region was for west africa but am only analysing the region of Ghana. tried the sf package but could not install the package in my RStudio. I even tried merging Ghana's shapefile with the grid data extracted for Ghana to generate my map but returned an error message. tried this reprex, kindly check if it contains all my code and do share your thoughts on it.

There is a problem with your reprex, apparently you just made it with the first line of your code (that is all we can see), could you pleas check on this? maybe this reprex guide would be easier to understand for you.


the link is very helpful but I think posting my code (what I've done so far will provide a good overview of my problem). Is it possible I could just copy and paste my code directly and probably share a link to the data am working with?

Where exactly have you posted your code? the only thing I can see is one line of code with a library call

below are the codes I've used so far

## needed libraries

##importing near surface air temperature ctrl eraint data
setwd("F:/DISSERTATION FOLDER/rcm_data")
nsat <- nc_open("wa12clmN_eraint_ctrl_tas_1980_2009_DAYMEAN.nc")  ##nsat means near surface air temperature

##generating variables and attributes for rhum
lon <- ncvar_get(nsat, "lon")
lat <- ncvar_get(nsat, "lat")
tnsat <- ncvar_get(nsat, "time")
atnsat <- tnsat/24 ##atnsat means actual time
atnsat <- as.Date(atnsat, origin="1970-1-1")  ###actual date begining 1980-01-01

####Extracting the nsat for the grid location for Ghana and rhum array for all the years
lon_rng<- c(-3.50,1.31)
lat_rng<- c(4.45,11.30)

lat_ind <- which(lat >= lat_rng[1] & lat<= lat_rng[2])
lon_ind<- which(lon >= lon_rng[1] & lon <=lon_rng[2])

nsat.array <- ncvar_get(nsat, "tas", start = c(1,1,1), count = c(length(lon_ind), length(lat_ind), 10958))
nsat.array <- nsat.array-273.15

I can not reproduce your code, but allow me to illustrate the approach on a similar use case; I have used temperature data from Copernicus and cropped it to shape of the Czech Republic from GADM.

This approach requires only two packages (raster and sf) + tidyverse, just because :))

It uses two steps:

  • remove the extra data points via raster::mask()
  • crop the file down to size via raster::crop()
library(tidyverse) # because tidyverse :)
library(raster)    # raster spatial data processing
library(sf)        # vector spatial data processing

data <- raster("./src/tg_0.25deg_day_2019_grid_ensmean.nc") # your ncdf file

borders <- readRDS("./src/gadm36_CZE_0_sf.rds") # country borders in sf format

plot(data) # the big picture

data_masked <- mask(data,borders) %>% # mask the unwanted areas
  crop(borders) # crop to shape

plot(data_masked) # the small picture


Hello Jindra

Many thanks for your help. The information was very useful. Unfortunately, the "sf" library fails to load in my RStudio though the programme has been installed. Thus, I used the "sp" function which did work. Below is my code

data <- raster("wa12clmN_eraint_ctrl_tas_1980_2009_DAYMEAN.nc") # your ncdf file

borders <- readRDS("F:/DISSERTATION FOLDER/rcm_data/gadm36_GHA_1_sp.rds") # country borders in sf format


plot(data) # the big picture

data_masked <- mask(data, borders) ##mask the unwanted areas

tempgh <- plot(data_masked, main = "Temperature anomaly of Ghana") # the small picture

With these outputs, I can rework my data and hopefully produce better temperature maps. Really grateful for your help and would reach out should I have any dilemma

Will rework the shape of the map to map it bigger

Glad to be of service!

The {sp} is a good package, and it did the job. You may want to persevere with the newer {sf} package though, as it is the current best practice and allows the use of goodies like geom_sf, which I am sure would make your dissertation more appealing.

To give you a taste of that look here: Bivariate maps with ggplot2 and sf

The reason the map retains the original extent is that you did not crop it after masking.

Consider adding the command like this:

data <- raster("wa12clmN_eraint_ctrl_tas_1980_2009_DAYMEAN.nc") # your ncdf file

borders <- readRDS("F:/DISSERTATION FOLDER/rcm_data/gadm36_GHA_1_sp.rds") # country borders in sp format


plot(data) # the big picture

data_masked <- mask(data, borders) # mask the unwanted areas
data_masked <- crop(data_masked, borders) # crop the image down to size

tempgh <- plot(data_masked, main = "Temperature anomaly of Ghana") # the small picture

Best of luck with your dissertation! :slightly_smiling_face:

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.