Converting CSV file to shapefile - but want polygon not points

对着背影说爱祢 提交于 2020-06-27 05:35:46

问题


I have a csv dataframe with the coordinates of a square. I have converted the csv into a shapefile, but it plots as four separate points and I want the plot to show a square.

  Shape long lat
1   1.1   43  10
2   1.1   43  13
3   1.1   40  13
4   1.1   40  10

I have converted it into a shapefile and given it a coordinate reference system as follows:

test <- as.data.frame(read_csv("/Users/alan/Desktop/Test.csv"))
Coord_Ref <- st_crs(3035)
plot_locations_test <- st_as_sf(test, coords = c("long", "lat"), crs =Coord_Ref)

Then I can plot the shapefile using ggplot

ggplot() +geom_sf(data = plot_locations_test)

And I get this plot

How can I make this a filled in square rather than seperate dots?


回答1:


You need to create a simple polygon from the data points, ensuring that the shape is closed (i.e. the first point must be the same as the last point). You convert the longitude / latitude columns to a matrix and put it in a list to pass to st_polygon.

Once you have created your polygon, you need to convert it to sfc using st_sfc:

test <- as.matrix(rbind(test[,-1], test[1, -1]))

Coord_Ref <- st_crs(3035)
plot_locations_test <- st_polygon(x = list(test))
plot_locations_test <- st_sfc(plot_locations_test, crs = Coord_Ref)
ggplot(plot_locations_test) + geom_sf(fill = "red", alpha = 0.1)

Data

test <- structure(list(Shape = c(1.1, 1.1, 1.1, 1.1), 
                       long = c(43L, 43L, 40L, 40L), 
                       lat = c(10L, 13L, 13L, 10L)), 
                  class = "data.frame", 
                  row.names = c("1", "2", "3", "4"))


来源:https://stackoverflow.com/questions/62327754/converting-csv-file-to-shapefile-but-want-polygon-not-points

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!