5
votes

I'm having trouble plotting a filled contour plot on top of a map with ggmap/ggplot2 in R.

My data are regularly spaced lat/lon coordinates with a z value indicating rainfall

> head( flood )
   lat       lon         rain
1 22.51916 -105.9318 1.486188e-05
2 22.59956 -105.9318 1.735962e-05
3 22.67996 -105.9318 2.024598e-05
4 22.76037 -105.9318 2.357599e-05
5 22.84077 -105.9318 2.741153e-05
6 22.92117 -105.9318 3.182212e-05

After getting the base map with ggmap, I'm trying to overplot filled contours of rain

map = ggmap( baseMap ) + 
    geom_contour( data = flood, aes( x = lon, y = lat, z = rain ) ) +
    scale_fill_continuous( name = "Rainfall (inches)", low = "yellow", high = "red" ) 

This gives me an error of

Error in unit(tic_pos.c, "mm") : 'x' and 'units' must have length > 0

If I do

map = ggmap( baseMap ) + 
    geom_contour( data = flood, aes( x = lon, y = lat, z = rain, fill = ..level.. ) ) +
    scale_fill_continuous( name = "Rainfall (inches)", low = "yellow", high = "red" ) 

I get this plot without the actual fill. enter image description here

I've been trying to follow this post and this post, but I can't get it right for my problem. I don't know much about ggplot/R, but I've been able to stumble through it so far up to now. What does ..level.. mean?

I think this post may be related, but I can't generalize the fix to work for contour plots.

1

1 Answers

8
votes

It's impossible to test without a more representative dataset (can you provide a link?).

Nevertheless, try:

## not tested..
map = ggmap( baseMap ) + 
    stat_contour( data = flood, geom="polygon", 
                  aes( x = lon, y = lat, z = rain, fill = ..level.. ) ) +
    scale_fill_continuous( name = "Rainfall (inches)", low = "yellow", high = "red" ) 

The problem is that geom_contour doesn't respect fill=.... You need to use stat_contour(...) with geom="polygon" (rather than "line").