Seydel
Seydel

Reputation: 31

How do I plot my shape with a list of polygons with ggplot2?

It’s my first time working with spatial data. The goal of my project is to visualise the price evolution of the housing market in the city of Mechelen (Belgium). I want to visualise this colour coded over a geographic map with different neighborhoods in the city.

I received a shape file (.shp) from the city which would visualise all different neighborhoods and I’m able to import it using the sf package, but I fail to plot it using the ggplot2 package.

Please find my current code below:

library(sf)
library(ggplot2)

#WORKING PART - reading the shape file
shapefile_df <- “/filepath.shp" %>%
  st_read()

#NOT WORKING PART - plotting the shapefile
map <- ggplot() +
  geom_polygon(data = shapefile_df, 
               aes(x = long, y = lat, group = group),
               color = 'gray', fill = 'white', size = .2)

print(map)

When reading the shape file I get a 4 column dataframe with the 4th column being a list of polygons called geometry.

My question: how do I get the long and lat from this list of polygons? Or am I completely looking from a wrong perspective?

For your reference when I enter shapefile_df$geometry RStudio responds with:

Geometry set for 12 features 
geometry type:  POLYGON
dimension:      XY
bbox:           xmin: 4.370086 ymin: 50.99116 xmax: 4.549005 ymax: 51.07861
epsg (SRID):    4326
proj4string:    +proj=longlat +datum=WGS84 +no_defs
First 5 geometries:
POLYGON ((4.471225 51.03026, 4.471367 51.03, 4....
POLYGON ((4.496646 51.02285, 4.496969 51.02247,...
POLYGON ((4.484093 51.01383, 4.484615 51.01353,...
POLYGON ((4.450368 51.0356, 4.450477 51.03558, ...
POLYGON ((4.439164 51.0608, 4.439563 51.06049, ...

Can anyone help out? I figured it might be useful I shared the shape file. Is there a best practice for sharing files here?

Please bear in mind that this is my first post and I’ve read a lot about asking questions correctly here, please give feedback if some of the explanation/code isn’t minimalistic enough.

Upvotes: 1

Views: 3870

Answers (1)

mrhellmann
mrhellmann

Reputation: 5529

You're looking at it wrong, but don't worry. It is easier than you think.

Shapefiles & sf objects are a little different than ususal data.frames. The geom_sf knows how to plot the points, lines, and polygons without you having to tell it exactly what to do.

To get your plot to work:

#start with a basic plot:
ggplot() +
  geom_sf(data = shapefile_df)

From there you can add color, fill, size, etc. arguments.

It looks like your data is made up of polygons, so expect to see something like this, but with the neighborhood borders from your area.

nc

Plot from example data from the sf package.

Upvotes: 4

Related Questions