Reputation: 145
I'm new to geo spatial analysis, and am having trouble reading my SHP file correctly when trying to do overlay plots with ggplot2.
For example, if I use the .shp file from http://thematicmapping.org/downloads/TM_WORLD_BORDERS_SIMPL-0.3.zip
And read my data using readOGR()
from the rgdal
package
shape_x <- readOGR("TM_WORLD_BORDERS_SIMPL-0.3.shp")
I can draw the following using base R
plot(shape_x)
But when I try using ggplot
, I get something funky:
ggplot() +
geom_polygon(data=as.data.frame(shape_x), aes(shape_x$LON, shape_x$LAT),
fill="white", colour="black")
I'm sure I'm missing something simple, I'm not sure how to specify the correct xy coordinates in aes()
in geom_polygon()
Thank you in advance!
Upvotes: 2
Views: 59
Reputation: 78927
Here is another approach using the sf
package:
library(sf)
shape_x <- st_read("TM_WORLD_BORDERS_SIMPL-0.3.shp")
ggplot() +
geom_sf(data = shape_x)
In case you insist to do it with
rgdal
then we have to bring the shape data in a certain form so that ggplot can read it: (we use broom::tidy
for this):
library(rgdal)
library(ggplot2)
library(broom)
url <- "http://thematicmapping.org/downloads/TM_WORLD_BORDERS_SIMPL-0.3.zip"
destfile <- "TM_WORLD_BORDERS_SIMPL-0.3.zip"
download.file(url, destfile)
unzip(destfile)
shape_x <- readOGR("TM_WORLD_BORDERS_SIMPL-0.3.shp")
shape_x_df <- tidy(shape_x)
ggplot() +
geom_polygon(data = shape_x_df,
aes(x = long, y = lat, group = group),
fill = "white", color = "black")
Upvotes: 1