How to plot a spatially explicit hdf5 file? - r - raster

589 views Asked by At

I have an hdf5 data file that has lat/long and a dozen of values, for example temperature. I would like to plot so I can visualize the data in a map style so with lat/long in the axis. Is there a direct way to do it? I only found a very complicated way on a blog. With netcdf data I can just use plot(ncvariable) and it will work, not with a hdf5 file.

I am using the rhdf5. If I read the h5 file and a specific value I only get a vector

> library(rhdf5)
> ncep<-h5read("CB_OL1_1979OCT.h5", "sh")
> head(ncep)
[1]  1.03953242  0.79024571  2.29503083  0.43957919  0.36909071 -0.04498866

I am attaching the file. I am not sure you would call it a 3d, it's a simple raster with x,y,value. h5 file

1

There are 1 answers

0
dimfalk On BEST ANSWER

It's been some time since you asked, but in case you did not found a solution yet, I'd like to provide two approaches on how to handle this.

Since your hdf5 file is not available anymore, I just picked a random file provided here for illustration.

On the one hand, you could simply use plot(grid = TRUE) from {terra} after having read your hdf5 file using rast():

library(terra)
#> terra 1.6.17

# read netcdf file
r <- rast("AMSR_E_L3_DailyOcean_V04_20020619.hdf") 

# get layer names
names(r)
#> [1] "Very_low_res_sst" "Low_res_sst"      "Low_res_wind"     "Med_res_wind"    
#> [5] "Med_res_vapor"    "High_res_cloud"   "RFI_angle"

# subset dataset by layer name
rs <- r[["Med_res_vapor"]]
rs
#> class       : SpatRaster 
#> dimensions  : 720, 1440, 1  (nrow, ncol, nlyr)
#> resolution  : 0.25, 0.25  (x, y)
#> extent      : -180, 180, -90, 90  (xmin, xmax, ymin, ymax)
#> coord. ref. : lon/lat Unknown datum based upon the Clarke 1866 ellipsoid 
#> source      : AMSR_E_L3_DailyOcean_V04_20020619.hdf:GlobalGrid:Med_res_vapor 
#> varname     : AMSR_E_L3_DailyOcean_V04_20020619 
#> name        : Med_res_vapor

plot(rs, grid = TRUE)

Or you could go for the little bit more complex solution, generating graticules manually using sf::st_graticules() first, followed by making use of {tidyterra} to be able to use {ggplot2} with SpatRaster and SpatVector objects from {terra}:

library(sf)
#> Linking to GEOS 3.9.1, GDAL 3.4.3, PROJ 7.2.1; sf_use_s2() is TRUE
library(ggplot2)
library(tidyterra)

grat <- st_graticule(lon = seq(-180, 180, 30),
                     lat = seq(-90, 90, 30),
                     ndiscr = 100) |> 
  st_transform("epsg:4326") |> 
  vect()

ggplot() +
  geom_spatraster(data = rs) +
  geom_spatvector(data = grat, color = alpha("grey60", 0.5)) +
  coord_sf(expand = FALSE) +
  scale_x_continuous(breaks = seq(-180, 180, 30)) +
  scale_y_continuous(breaks = seq(-90, 90, 30))
#> SpatRaster resampled to ncells = 5e+05