-3

I manually entered latitude and longitude in my dataset in csv format and imported the dataset to R. I am trying convert the variable lat and lng into coordinates so that I can use tmap or geom_sf to plot it as a map in R. But I am not able to do so. I used the following code to convert the variables lat and lng to coordinates and it did not work. I am attaching the image of my dataset here. can someone help me? I want to plot variable lat and lng on a map.

cov2 <- st_as_sf(co1, coords = c('lng', 'lat'))


ggplot(co1) + 
  geom_sf()

coordinates(co1)<-6:7

enter image description here

jpsmith
  • 11,023
  • 5
  • 15
  • 36
  • Hi @Mahir Bhatt, as explicitly indicated when asking a question, please do not provide your data as an image. Please edit your question to provide reproducible code using something like `dput(your_data)` or creating a sample dataset. – jpsmith Nov 12 '22 at 12:59
  • You are converting `col` to `sf` and storing it in `cov2`, but then you are trying to plot your old `col`, not `cov2` – margusl Nov 12 '22 at 13:13
  • cov2%>%tm_shape() + tm_polygons(col= "Type"). I tried using this but this is also not working. – Mahir Bhatt Nov 12 '22 at 13:23
  • Again, you have have `ggplot(co1)` instead of `ggplot(cov2)` in your question. If you just want to have some points plotted, you can start with: `read_csv("lat, lng\n32.77610, -89.12210\n41.83730, -87.63620\n") %>% st_as_sf(coords = c("lng", "lat"), crs = st_crs(4326) ) %>% ggplot() + geom_sf()` – margusl Nov 12 '22 at 13:41
  • Hi, Thanks for the answer. I am able to plot points using this but I want to have them on a global map, not just as points on coordinate plane. Is that possible? – Mahir Bhatt Nov 12 '22 at 14:46
  • @jpsmith sorry for the inconvenience. Will keep that in mind next time – Mahir Bhatt Nov 12 '22 at 15:00
  • https://stackoverflow.com/a/74412129/646761 – margusl Nov 12 '22 at 15:41

1 Answers1

0

Based on the points defined by @margusl you can do the following:

library(tmap)
data("World")

points <- read_csv("lat, lng\n32.77610, -89.12210\n41.83730, -87.63620\n") %>% 
  st_as_sf(coords = c("lng", "lat"), crs = st_crs(4326))

tm_shape(World) +
  tm_polygons(col = "gray", 
              alpha = .5) +
  tm_shape(points) +
  tm_bubbles(col = "red", 
             border.col = "black", 
             size = .5)

enter image description here

mgrund
  • 1,415
  • 8
  • 10