San-Diego-WX
San-Diego-WX

Reputation: 235

How do I add state and county lines to a geom_raster ggplot in R?

I have a dataset (latitude,longitude,value) over S. California which I am able to plot using the ggplot (see below). Latitude ranges from 31.5 to 35.5 and longitude from -121 to -113. The ggplot map looks fine but I would like to add the state and county border lines to my map.

I have tried adding geom_polygon() but I keep getting the borders for the whole southwest USA instead of over my plot area only (S. California).

I was wondering if anyone would have any suggestions/ideas on how to do this. Thank you very much.

"df is a 3D dataframe (Lat,Lon,value) over S. California" "lat ranges from 31 to 35" "lon ranges from -121 to -113" "value ranges from 3000 to 5000"

library(maps)
library(fields)
library(ggplot2)    
state_map <- map_data("state")
bmap=map_data("state", xlim=c(-121,-113), ylim=c(31.5,35.5))

p1 = ggplot() + geom_raster(data = df, aes(x=Lon, y = Lat, fill=Value)) + 
     coord_fixed(ratio = 1) +
     geom_polygon(data=bmap,aes(x=long,y=lat,group=group), inherit.aes=F, 
     colour='black', fill=NA) +      
     scale_fill_gradientn(na.value="white",limits = c(3500,5000), 
                          colours=c("yellow","orange","green","blue")) +
     theme(panel.background = element_rect(fill = 'white',color="black"),
           legend.key = element_blank()) 
print(p1)

I am getting borders for the entire southwest but I'd like then only for my data area:

I am getting borders for the entire southwest but I'd like then only for my data area

Upvotes: 4

Views: 2021

Answers (1)

Marco Sandri
Marco Sandri

Reputation: 24272

You can zoom the map using coord_cartesian:

library(maps)
library(fields)
library(ggplot2)    
state_map <- map_data("state")
bmap=map_data("state", xlim=c(-121,-113), ylim=c(31.5,35.5))

# Create the df dataset with random numbers for Values
n <- 80
df <- expand.grid(seq(31,35,length.out=n),
            seq(-121,-113,length.out=n))
df$Vaule <- 3000+2000*runif(nrow(df))
names(df) <- c("Lat","Lon","Value")

p1 = ggplot() + 
     coord_fixed(ratio = 1) +
     geom_raster(data = df, aes(x=Lon, y = Lat, fill=Value), alpha=0.2) +   
     geom_polygon(data=bmap,aes(x=long,y=lat,group=group), inherit.aes=F, 
     colour='black', fill=NA, lwd=1) +      
     scale_fill_gradientn(na.value="white",limits = c(3500,5000), 
                          colours=c("yellow","orange","green","blue")) +
     scale_y_continuous(expand = c(0,0)) + 
     scale_x_continuous(expand = c(0,0)) + 
     theme(panel.background = element_rect(fill = 'white',color="black"),
           legend.key = element_blank()) +
     coord_cartesian(xlim=c(-121, -113), ylim=c(31,35)) +
     theme(panel.border = element_rect(colour = "gray50", fill=NA, size=1))
print(p1)

enter image description here

Upvotes: 2

Related Questions