Home > Back-end >  Plotting a matrix on ggmap with geom_tile not working
Plotting a matrix on ggmap with geom_tile not working

Time:02-23

I'm trying to plot a matrix (mostly random numbers with a few NAs) with longitude/latitude coordinates on a ggmap plot.

This is my code:

library(ggmap)
library(ggplot2)

define the longitude and latitude coordinates

x1=34.2
x2=42.4
y1=37.4
y2=29.4
lon = seq(x1,x2,by=0.1)
lat = seq(y1,y2,by=-0.1)

define a matrix with random numbers with the longitude/latitude dimensions

set.seed(1)
numbers = rnorm(length(lon)*length(lat))
var = matrix(numbers,length(lon),length(lat))

add some NAs to the matrix

var[1:5,1:5] = NA

lat_min <- min(lat)-0.3
lon_min <- min(lon)-0.3
lat_max <- max(lat) 0.3
lon_max <- max(lon) 0.3

construct the ggmap

map_box <- c(left=lon_min,bottom=lat_min,
            right=lon_max,top=lat_max)
total_stmap <- get_stamenmap(bbox=map_box,zoom=5,maptype="toner")
total_ggmap <- ggmap(total_stmap,extent="panel")

make a data.frame to attribute each matrix index to the geographical coordinate

lat_df <- c()
lon_df <- c()
var_df <- c()
for (i in 1:length(lon)) {
  for (j in 1:length(lat)) {
    lon_df <- c(lon_df,lon[i])
    lat_df <- c(lat_df,lat[j])
    var_df = var[i,j]
  }
}
df=data.frame(Longitude=lon_df,Latitude=lat_df,Variable=var_df)

make the plot using ggmap and geom_tile

plot = total_ggmap  
geom_tile(data=df,aes(x=Longitude,y=Latitude,fill=Variable),alpha=1/2,color="black",size=0)  
geom_sf(data = df, inherit.aes = FALSE, fill = NA)

With this code I get the message:

Coordinate system already present. Adding new coordinate system, which will replace the existing one.

...and a blank plot.

CodePudding user response:

There were two problems here. The first is that all of your values in the Variable column are the same, because you are just overwriting var_df with every iteration of your loop. The line

var_df = var[i,j]

Should be

var_df = c(var_df, var[i,j])

Secondly, you should not be using geom_sf if you have a data frame of longitude, latitude and value. geom_sf is used to plot sf objects, which is not what you have.

Instead, you need only do:

plot <- total_ggmap  
   geom_tile(data = df, aes(Longitude, Latitude, fill = Variable), alpha = 1/2, size = 0)

and you get:

plot

enter image description here

  • Related