Search code examples
rggplot2metr

The command geom_contour_fill fails to render in some cases in ggplot2


This is my first question so doing my best to make my question simple and reproducible.

I'm running into a problem with the R command geom_contour_fill from the metR library. The code below shows that geom_contour_fill fails to plot in some cases when geom_contour works just fine with the same input data. geom_contour_fill just returns a gray box in the plot pane.

However, by changing the zoom level to z = 9 in the get_elev_raster command in the code, geom_contour_fill works fine again.

I want to be able to use the higher zoom level and I've run into this problem randomly with other map extents, so can anyone see how to resolve the problem?

Thanks!

##loading necessary libraries
library(elevatr)
library(metR)
library(ggplot2)
library(raster)

##map limits
dims <- data.frame(long = c(-97.73235, -97.78369), lat = c(30.30242, 30.25396))

##grid point from map limits
grid <- data.frame(x = seq(from = dims$long[2], to = dims$long[1], length.out = 1000),
                   y = seq(from = dims$lat[2], to = dims$lat[1], length.out = 1000))

##coordinate system
nad27 <- "+proj=longlat +datum=NAD27 +no_defs +ellps=clrk66 +nadgrids=@conus,@alaska,@ntv2_0.gsb,@ntv1_can.dat"

##pull elevation data
elev <- get_elev_raster(grid, prj = nad27, z = 10, clip = "bbox")

##convert to data frame
elevDF <- as.data.frame(elev, xy = TRUE)

##remove NAs
elevDF <- elevDF[!is.na(elevDF$layer),]

##geom_contour runs fine
ggplot() + 
  geom_contour(data = elevDF, aes(x = x, y = y, z = layer), size = .5, binwidth = 5)

##geom_contour fill fails - plots blank gray area
ggplot() + 
  geom_contour_fill(data = elevDF, aes(x = x, y = y, z = layer), size = .5, binwidth = 5) 

Solution

  • I found by experimentation and guessing that I could get some results with a seq argument to breaks:

    png(); print( ggplot() + 
                  geom_contour_fill(data = elevDF, 
                    aes(x = x, y = y, z = layer), breaks =seq(150,175,by=5), size = .5, binwidth = 5) );dev.off()
    

    I didn't get much help from the help page and instead tried searching "geom_contour_filled metr", finding the vignette page at https://cran.r-project.org/web/packages/metR/vignettes/Visualization-tools.html and then trying out first the fill and then the breaks parameters to see what I could get. Specifying a single value for breaks only succeeds if it is in the range of the z data and specifying a value outside that range throws an uninformative (to me anyway) error.:

    enter image description here