0

I have found myself with a data.frame containing a column of lists. Within these lists are the coordinates for a polygon; the remainder of the columns are the features of the polygons.

I would like to "spread out" the coordinate points in the lists so that I can use ggplot2 to plot the polygons and make a map, but am having trouble figuring out how to do this.

I don't really understand how the lists are structured and they are all different sizes, as the polygons have different shapes.

The data was originally a json file. I pulled it in with jsonlite package and then tried to boil it down to the relevant components like so:

library(jsonlite)

json_file <- "https://raw.githubusercontent.com/OpenOil-UG/concessionsmap/master/concessions/data/NG_contracts%2B.geojson" json_data <- jsonlite::fromJSON(json_file, simplifyDataFrame=T) data <- json_data$features data2 <- flatten(data)

This may not be the right approach starting with the json file. It is just what seemed most straightforward to me as far as taking the data from json to a data.frame I could understand.

*Edited to include real data instead of a sample

moman822
  • 1,904
  • 3
  • 19
  • 33
  • 1
    Not sure what you're asking. Base R already has a function to plot a polygon, documented at `?polygon`. Like `x = a[[1]][,,1]; y = a[[1]][,,2]; plot(NULL, xlim=range(x), ylim=range(y)); polygon(x,y,col="blue")` – Frank Sep 06 '16 at 20:21
  • How did you wind up with such a data structure in the first place? You seem to have a three-dimensional array. It would help if you included some sort of [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). It's not clear how what you've provided is a row of a data.frame. Give the desired output for your sample input. – MrFlick Sep 06 '16 at 20:28

1 Answers1

2

I would like to [...] use ggplot2 to plot the polygons and make a map

One option:

library(geojsonio)
library(ggplot2)
download.file(json_file, tf <- tempfile(fileext = ".geojson"))
df <- fortify(geojson_read(tf, what="sp"))
ggplot(df, aes(long, lat, group=group)) + 
  geom_polygon(color="white")

That gives you:

enter image description here

lukeA
  • 53,097
  • 5
  • 97
  • 100
  • That's really great and works to plot, but it loses all of the other attributes from the original .json besides the coordinates; is there a way to keep those as well or get them in a different data.frame to link back with an id variable? – moman822 Sep 07 '16 at 12:47
  • 1
    `spdf <- geojson_read(tf, what="sp");df <- fortify(spdf);df <- merge(df, spdf, by.x="id", by.y="row.names")`? – lukeA Sep 07 '16 at 13:36