rheatmaprgooglemaps

Plotting z as a color with R on a rGoogleMap


I have a function and I want to plot only x and y. z should be represented as a color. Is there a package that does the work for me ?

f = function(a,b){
   dnorm(a^2+b^2)
}


x = seq(-2, 2, 0.1)
y = seq(-2, 2, 0.1)
z = outer(x, y, f)
persp(x, y, z)

I want to plot this function on a map generated with rGoogleMaps. Maybe there is a more specific package for this use?


Solution

  • Something like this?

    library(ggmap)         # loads ggplot2 as well
    library(RgoogleMaps)   # for getGeoCode
    london.center <- getGeoCode("London")
    london <- get_map("London", zoom=12)
    x    <- seq(-2,2,0.1)
    df   <- expand.grid(x=x,y=x)
    df$z <- with(df,f(x,y))
    df$x <- london.center[2]+df$x/20
    df$y <- london.center[1]+df$y/20
    
    ggp <- ggmap(london)+
      geom_tile(data=df,aes(x=x,y=y,fill=z), alpha=0.2)+
      scale_fill_gradientn(guide="none",colours=rev(heat.colors(10)))+
      stat_contour(data=df, aes(x=x, y=y, z=z, color=..level..), geom="path", size=1)+
      scale_color_gradientn(colours=rev(heat.colors(10)))
    plot(ggp)
    

    This solution uses ggplot. Perhaps someone else will show you how to do this using RgoogleMaps.

    Basically, we load the map, using get_map(...) (which is just a wrapper for GetMap(...) in the RgoogleMaps package).

    Then we create the sample data frame df, which contains three columns, x, y, and z, and one row for every combination of x and y (this is the format required by ggplot).

    Then we create the map layers. First the map itself, using ggmap(...); then a layer of tiles "filled" based on the value of z, using geom_tile(...); then a set of contour lines colored using the value of z, using stat_contour(geom="path",...). The rest of the code sets the fill and line colors and renders the map.

    Purists will tell you that you can render the filled contours directly using stat_contour(geom="polygon",...), instead of using tiles, but this has the unfortunate effect of clipping any contours not completely enclosed in the plot area.