问题
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