Home > other >  How to plot coordinates over a shape file in R?
How to plot coordinates over a shape file in R?

Time:11-18

a little new to this so any help would be greatly appreciated. I've loaded a shapefile of all the countries in the world and plotted it. However, I'm having trouble adding a bunch of points from coordinates to the plot. Any help in how to fix this would be greatly appreciated.

Code so far

MeteoriteData <- read.csv("C:/Users/ChaseDickson_/Desktop/College/AERO 689/Semester Project/Meteorite Landings.csv")
MeteoriteData$lat <- as.factor(MeteoriteData$lat)
MeteoriteData$long <- as.factor(MeteoriteData$long)

world <- st_read("C:/Users/ChaseDickson_/Desktop/College/AERO 689/Semester Project/TM_WORLD_BORDERS_SIMPL-0.3/TM_WORLD_BORDERS_SIMPL-0.3.shp")

world <- st_transform(world, crs = 4326)
ggplot()  
  geom_sf(data = world)  
  theme_bw()

This returns the plot that is attached.

enter image description here

I've tried using

ggplot()  
  geom_sf(data = world)  
  theme_bw()  
  geom_point(data = MeteoriteData, aes(x = lat, y = long)

but that doesn't seem to work as it gives me this error

Error in `calc_limits_bbox()`:
! Scale limits cannot be mapped onto spatial coordinates in `coord_sf()`
ℹ Consider setting `lims_method = "geometry_bbox"` or `default_crs = NULL`.

CodePudding user response:

Three issues I can see with your code:

1/

MeteoriteData$lat <- as.factor(MeteoriteData$lat)

Do you need to convert your lat and long data to factors? I've never seen that done before and I suspect it will only lead to trouble.

2/

geom_point(data = MeteoriteData, aes(x = lat, y = long)

Looks like you've got your x/y and long/lat around the wrong way. x should be long and y should be lat.

3/

As r2evans says, you need a closing parenthesis on this line:

geom_point(data = MeteoriteData, aes(x = lat, y = long)

Try this code:

require('sf')

# Read in data from .csv file
MeteoriteData <- read.csv("C:/Users/ChaseDickson_/Desktop/College/AERO 689/Semester Project/Meteorite Landings.csv")

# Convert these points to an SF object, specifying the X and Y
#  column names, and supplying the CRS as 4326 (which is WGS84)
MeteoriteData <- st_as_sf(MeteoriteData, coords=c('long', 'lat'), crs=4326)

# Read in the world shape file and convert it to the same CRS
world <- st_read("C:/Users/ChaseDickson_/Desktop/College/AERO 689/Semester Project/TM_WORLD_BORDERS_SIMPL-0.3/TM_WORLD_BORDERS_SIMPL-0.3.shp")
world <- st_transform(world, crs = 4326)

# Plot it
ggplot()  
  geom_sf(data = world)  
  geom_sf(data = MeteoriteData)  
  theme_bw()

Note: I don't have access to your data files so this code is from memory and untested but should get you on the right path.

  • Related