This lesson is being piloted (Beta version)

Raster Time Series Data in R

Overview

Teaching: 40 min
Exercises: 20 min
Questions
  • How can I view and and plot data for different times of the year?

Objectives
  • Understand the format of a time series raster dataset.

  • Work with time series rasters.

  • Import a set of rasters stored in a single directory.

  • Create a multi-paneled plot.

  • Convert character data to date format.

Things You’ll Need To Complete This Episode

See the lesson homepage for detailed information about the software, data, and other prerequisites you will need to work through the examples in this episode.

This episode covers how to work with and plot a raster time series, using an R RasterStack object. It also covers practical assessment of data quality in remote sensing derived imagery.

About Raster Time Series Data

A raster data file can contain one single band or many bands. If the raster data contains imagery data, each band may represent reflectance for a different wavelength (color or type of light) or set of wavelengths - for example red, green and blue. A multi-band raster may two or more bands or layers of data collected at different times for the same extent (region) and of the same resolution. For this episode, we will work with a time series of normalized difference vegetation index (NDVI) and RGB data from the Harvard Forest site. We introduced the concepts of NDVI and RGB data in an earlier lesson and worked with an RGB RasterStack in the Work with Multi-band Rasters in R episode.

In this episode, we will:

  1. Import NDVI data in GeoTIFF format.
  2. Import, explore and plot NDVI data derived for several dates throughout the year.
  3. View the RGB imagery used to derived the NDVI time series to better understand unusual / outlier values.

RGB Data

While the NDVI data is a single band product, the RGB images that contain the red band used to derive NDVI, contain 3 (of the 7) 30m resolution bands available from Landsat data. The RGB directory contains RGB images for each time period that NDVI is available.

Getting Started

In this episode, we will use the raster, rgdal, reshape, and scales packages. Make sure you have them loaded.

library(raster)
library(rgdal)
library(reshape)
library(scales)

To begin, we will create a list of raster files using the list.files() function. This list will be used to generate a RasterStack. We will only add files that have a .tif extension to our list. To do this, we will use the syntax pattern=".tif$". If we specify full.names = TRUE, the full path for each file will be added to the list.

Data Tip

In the pattern above, the $ character represents the end of a line. Using it ensures that our pattern will only match files that end in .tif. This pattern matching uses a language called “regular expressions”, which is beyond the scope of this workshop.

NDVI_HARV_path <- "data/NEON-DS-Landsat-NDVI/HARV/2011/NDVI"

all_NDVI_HARV <- list.files(NDVI_HARV_path,
                            full.names = TRUE,
                            pattern = ".tif$")

It’s a good idea to look at the file names that matched our search to make sure they meet our expectations.

all_NDVI_HARV
character(0)

Now we have a list of all GeoTIFF files in the NDVI directory for Harvard Forest. Next, we will create a RasterStack from this list using the stack() function. We introduced the stack() function in an earlier episode.

NDVI_HARV_stack <- stack(all_NDVI_HARV)
Error in x[[1]]: subscript out of bounds

We can explore the GeoTIFF tags (the embedded metadata) in a stack using the same syntax that we used on single-band raster objects in R including: crs() (coordinate reference system), extent() and res() (resolution; specifically yres() and xres()).

crs(NDVI_HARV_stack)
Error in crs(NDVI_HARV_stack): object 'NDVI_HARV_stack' not found

The CRS for our stack is +proj=utm +zone=19 +ellps=WGS84 +units=m +no_defs. The CRS is in UTM Zone 19. If you have completed the previous episodes in this workshop, you may have noticed that the UTM zone for the NEON collected remote sensing data was in Zone 18 rather than Zone 19. Why are the Landsat data in Zone 19?

Source: National Ecological Observatory Network (NEON).

A Landsat scene is extremely wide - spanning over 170km north to south and 180km east to west. This means that Landsat data often cover multiple UTM zones. When the data are processed, the zone in which the majority of the data cover is the zone which is used for the final CRS. Thus, our field site at Harvard Forest is located in UTM Zone 18, but the Landsat data is in a CRS of UTM Zone 19.

Challenge: Raster Metadata

Investigate the metadata for our RasterStack and answer the following questions.

  1. What are the x and y resolution of the data?
  2. What units are the above resolution in?

Answers

extent(NDVI_HARV_stack)
Error in extent(NDVI_HARV_stack): object 'NDVI_HARV_stack' not found
yres(NDVI_HARV_stack)
Error in yres(NDVI_HARV_stack): object 'NDVI_HARV_stack' not found
xres(NDVI_HARV_stack)
Error in xres(NDVI_HARV_stack): object 'NDVI_HARV_stack' not found

Plotting Time Series Data

Once we have created our RasterStack, we can visualize our data. We can use the ggplot() command to create a multi-panelled plot showing each band in our RasterStack. First we need to create a data frame object. Because there are multiple bands in our data, we will reshape (or “melt”) the data so that we have a single column with the NDVI observations. We will use the function melt() from the reshape package to do this:

NDVI_HARV_stack_df <- as.data.frame(NDVI_HARV_stack, xy = TRUE) %>%
    melt(id.vars = c('x','y'))
Error in as.data.frame(NDVI_HARV_stack, xy = TRUE): object 'NDVI_HARV_stack' not found

Now we can plot our data using ggplot(). We want to create a separate panel for each time point in our time series, so we will use the facet_wrap() function to create a multi-paneled plot:

ggplot() +
  geom_raster(data = NDVI_HARV_stack_df , aes(x = x, y = y, fill = value)) +
  facet_wrap(~ variable)
Error in fortify(data): object 'NDVI_HARV_stack_df' not found

Look at the range of NDVI values observed in the plot above. We know that the accepted values for NDVI range from 0-1. Why does our data range from 0 - 10,000?

Scale Factors

The metadata for this NDVI data specifies a scale factor: 10,000. A scale factor is sometimes used to maintain smaller file sizes by removing decimal places. Storing data in integer format keeps files sizes smaller.

Let’s apply the scale factor before we go any further. Conveniently, we can quickly apply this factor using raster math on the entire stack as follows:

NDVI_HARV_stack <- NDVI_HARV_stack/10000
Error in eval(expr, envir, enclos): object 'NDVI_HARV_stack' not found

After applying our scale factor, we can recreate our plot using the same code we used above.

NDVI_HARV_stack_df <- as.data.frame(NDVI_HARV_stack, xy = TRUE) %>%
    melt(id.vars = c('x','y'))
Error in as.data.frame(NDVI_HARV_stack, xy = TRUE): object 'NDVI_HARV_stack' not found
ggplot() +
  geom_raster(data = NDVI_HARV_stack_df , aes(x = x, y = y, fill = value)) +
  facet_wrap(~variable)
Error in fortify(data): object 'NDVI_HARV_stack_df' not found

Take a Closer Look at Our Data

Let’s take a closer look at the plots of our data. Massachusetts, where the NEON Harvard Forest Field Site is located, has a fairly consistent fall, winter, spring, and summer season where vegetation turns green in the spring, continues to grow throughout the summer, and begins to change colors and senesce in the fall through winter. Do you notice anything that seems unusual about the patterns of greening and browning observed in the plots above?

Hint: the number after the “X” in each tile title is the Julian day which in this case represents the number of days into each year. If you are unfamiliar with Julian day, check out the NEON Data Skills Converting to Julian Day tutorial.

View Distribution of Raster Values

In the above exercise, we viewed plots of our NDVI time series and noticed a few images seem to be unusually light. However this was only a visual representation of potential issues in our data. What is another way we can look at these data that is quantitative?

Next we will use histograms to explore the distribution of NDVI values stored in each raster.

ggplot(NDVI_HARV_stack_df) +
  geom_histogram(aes(value)) +
    facet_wrap(~variable)
Error in ggplot(NDVI_HARV_stack_df): object 'NDVI_HARV_stack_df' not found

It seems like things get green in the spring and summer like we expect, but the data at Julian days 277 and 293 are unusual. It appears as if the vegetation got green in the spring, but then died back only to get green again towards the end of the year. Is this right?

Explore Unusual Data Patterns

The NDVI data that we are using comes from 2011, perhaps a strong freeze around Julian day 277 could cause a vegetation to senesce early, however in the eastern United States, it seems unusual that it would proceed to green up again shortly thereafter.

Let’s next view some temperature data for our field site to see whether there were some unusual fluctuations that may explain this pattern of greening and browning seen in the NDVI data. First we will read in the temperature data and preview the structure of that dataframe:

har_met_daily <-
  read.csv("data/NEON-DS-Met-Time-Series/HARV/FisherTower-Met/hf001-06-daily-m.csv")
Warning in file(file, "rt"): cannot open file 'data/NEON-DS-Met-Time-Series/
HARV/FisherTower-Met/hf001-06-daily-m.csv': No such file or directory
Error in file(file, "rt"): cannot open the connection
str(har_met_daily)
Error in str(har_met_daily): object 'har_met_daily' not found

The date column is currently coded as a factor. We want to be able to treat it as a date, so we will use the as.Date() function to convert it. We need to tell R what format the data is in. Our dates are YYY-MM-DD, which is represented by R as %Y-%m-%d.

har_met_daily$date <- as.Date(har_met_daily$date, format = "%Y-%m-%d")
Error in as.Date(har_met_daily$date, format = "%Y-%m-%d"): object 'har_met_daily' not found

We only want to look at the data from 2011:

yr_11_daily_avg <- subset(har_met_daily,
                            date >= as.Date('2011-01-01') &
                            date <= as.Date('2011-12-31'))
Error in subset(har_met_daily, date >= as.Date("2011-01-01") & date <= : object 'har_met_daily' not found

Now we can plot the air temperature (the airt column) by Julian day (the jd column):

ggplot() +
  geom_point(data = yr_11_daily_avg, aes(jd, airt)) +
  ggtitle("Daily Mean Air Temperature",
          subtitle = "NEON Harvard Forest Field Site") +
  xlab("Julian Day 2011") +
  ylab("Mean Air Temperature (C)")
Error in fortify(data): object 'yr_11_daily_avg' not found

There are no significant peaks or dips in the temperature during the late summer or early fall time period that might account for patterns seen in the NDVI data. Let’s have a look at the source Landsat imagery that was partially used used to derive our NDVI rasters to try to understand what appear to be outlier NDVI values.

Error in .local(.Object, ...) : 
Error in .rasterObjectFromFile(x, objecttype = "RasterBrick", ...): Cannot create a RasterLayer object from this file. (file does not exist)
Error in as.data.frame(RGB_133, xy = TRUE): object 'RGB_133' not found
Error in quantile(RGB_133_df$X133_HARV_landRGB.1, quantiles, na.rm = TRUE): object 'RGB_133_df' not found
Error in quantile(RGB_133_df$X133_HARV_landRGB.2, quantiles, na.rm = TRUE): object 'RGB_133_df' not found
Error in quantile(RGB_133_df$X133_HARV_landRGB.3, quantiles, na.rm = TRUE): object 'RGB_133_df' not found
Error in eval(expr, envir, enclos): object 'RGB_133_df' not found
Error in eval(expr, envir, enclos): object 'RGB_133_df' not found
Error in eval(expr, envir, enclos): object 'RGB_133_df' not found
Error in tempR[tempR < 0] <- 0: object 'tempR' not found
Error in tempG[tempG < 0] <- 0: object 'tempG' not found
Error in tempB[tempB < 0] <- 0: object 'tempB' not found
Error in tempR[tempR > 1] <- 1: object 'tempR' not found
Error in tempG[tempG > 1] <- 1: object 'tempG' not found
Error in tempB[tempB > 1] <- 1: object 'tempB' not found
Error in rgb(tempR, tempG, tempB): object 'tempR' not found
Error in layer(data = data, mapping = mapping, stat = stat, geom = GeomRaster, : object 'RGB_133_df' not found
Error in .local(.Object, ...) : 
Error in .rasterObjectFromFile(x, objecttype = "RasterBrick", ...): Cannot create a RasterLayer object from this file. (file does not exist)
Error in eval(expr, envir, enclos): object 'RGB_197' not found
Error in as.data.frame(RGB_197, xy = TRUE): object 'RGB_197' not found
Error in quantile(RGB_197_df$X197_HARV_landRGB.1, quantiles, na.rm = TRUE): object 'RGB_197_df' not found
Error in quantile(RGB_197_df$X197_HARV_landRGB.2, quantiles, na.rm = TRUE): object 'RGB_197_df' not found
Error in quantile(RGB_197_df$X197_HARV_landRGB.3, quantiles, na.rm = TRUE): object 'RGB_197_df' not found
Error in eval(expr, envir, enclos): object 'RGB_197_df' not found
Error in eval(expr, envir, enclos): object 'RGB_197_df' not found
Error in eval(expr, envir, enclos): object 'RGB_197_df' not found
Error in tempR[tempR < 0] <- 0: object 'tempR' not found
Error in tempG[tempG < 0] <- 0: object 'tempG' not found
Error in tempB[tempB < 0] <- 0: object 'tempB' not found
Error in tempR[tempR > 1] <- 1: object 'tempR' not found
Error in tempG[tempG > 1] <- 1: object 'tempG' not found
Error in tempB[tempB > 1] <- 1: object 'tempB' not found
Error in rgb(tempR, tempG, tempB): object 'tempR' not found
Error in layer(data = data, mapping = mapping, stat = stat, geom = GeomRaster, : object 'RGB_197_df' not found

Challenge: Examine RGB Raster Files

Plot the RGB images for the Julian days 277 and 293. Compare those with the RGB plots for Julian days 133 and 197 (shown above). Does the RGB imagery from these two days explain the low NDVI values observed on these days?

Answers

First we need to load in the RGB data for Julian day 277 and look at its metadata.

RGB_277 <- stack("data/NEON-DS-Landsat-NDVI/HARV/2011/RGB/277_HARV_landRGB.tif")
Error in .local(.Object, ...) : 
Error in .rasterObjectFromFile(x, objecttype = "RasterBrick", ...): Cannot create a RasterLayer object from this file. (file does not exist)
RGB_277
Error in eval(expr, envir, enclos): object 'RGB_277' not found

The RGB data has a max value of 255, but we need our color intensity to be between 0 and 1, so we will divide our RasterStack object by 255.

RGB_277 <- RGB_277/255
Error in eval(expr, envir, enclos): object 'RGB_277' not found

Next we convert it to a dataframe.

RGB_277_df <- as.data.frame(RGB_277, xy = TRUE)
Error in as.data.frame(RGB_277, xy = TRUE): object 'RGB_277' not found

We create RGB colors from the three channels:

RGB_277_df$rgb <- with(RGB_277_df, rgb(X277_HARV_landRGB.1, X277_HARV_landRGB.2, X277_HARV_landRGB.3,1))
Error in with(RGB_277_df, rgb(X277_HARV_landRGB.1, X277_HARV_landRGB.2, : object 'RGB_277_df' not found

Finally, we can plot the RGB data for Julian day 277.

ggplot() +
  geom_raster(data=RGB_277_df, aes(x, y), fill=RGB_277_df$rgb) + 
  ggtitle("Julian day 277") 
Error in layer(data = data, mapping = mapping, stat = stat, geom = GeomRaster, : object 'RGB_277_df' not found

We then do the same steps for Julian day 293

# Julian day 293
RGB_293 <- stack("data/NEON-DS-Landsat-NDVI/HARV/2011/RGB/293_HARV_landRGB.tif")
Error in .local(.Object, ...) : 
Error in .rasterObjectFromFile(x, objecttype = "RasterBrick", ...): Cannot create a RasterLayer object from this file. (file does not exist)
RGB_293 <- RGB_293/255
Error in eval(expr, envir, enclos): object 'RGB_293' not found
RGB_293_df <- as.data.frame(RGB_293, xy = TRUE)
Error in as.data.frame(RGB_293, xy = TRUE): object 'RGB_293' not found
RGB_293_df$rgb <- with(RGB_293_df, rgb(X293_HARV_landRGB.1, X293_HARV_landRGB.2, X293_HARV_landRGB.3,1))
Error in with(RGB_293_df, rgb(X293_HARV_landRGB.1, X293_HARV_landRGB.2, : object 'RGB_293_df' not found
ggplot() +
  geom_raster(data = RGB_293_df, aes(x, y), fill = RGB_293_df$rgb) +
  ggtitle("Julian day 293")
Error in layer(data = data, mapping = mapping, stat = stat, geom = GeomRaster, : object 'RGB_293_df' not found

This example highlights the importance of exploring the source of a derived data product. In this case, the NDVI data product was created using Landsat imagery - specifically the red and near-infrared bands. When we look at the RGB collected at Julian days 277 and 293 we see that most of the image is filled with clouds. The very low NDVI values resulted from cloud cover — a common challenge that we encounter when working with satellite remote sensing imagery.

Key Points

  • Use the list.files() function to get a list of filenames matching a specific pattern.

  • Use the facet_wrap() function to create multi-paneled plots with ggplot2.

  • Use the as.Date() function to convert data to date format.