Use ggplot to plot polygon with holes (in a city map)

烂漫一生 提交于 2019-11-28 05:48:53

问题


I have 3 shp files for create a city map:

  • land.shp (polygon drawing the land which is above water)
  • road.shp (polygon drawing all the roads, note that some of them are "circular road", which means a hole is in the middle)
  • building.shp (polygon drawing all buildings)

I used QGIS to plot the map I want, then I use ggplot to play the land.shp, then road.shp and building shp to do it again. The one below is output from Google map to illustrate my issue:

You can see there are 2 bridges and some sea (I don't have sea shp, I just set the background to be blue) between them, tagged using blue dot. In R, that area should be a hole, but it is all filled with grey. The same issue go to the grey area tagged using red dot, which is a piece of land, and another grey area tagged using green dot, which is a building surrounded by road.

I will have land/sea/building in the hole of road.shp, I can't show them using R.

Can anyone teach me how to show the things behind the road.shp layer in R? Thanks.


回答1:


One common convention to draw polygons with holes is:

  • A closed polygon with points that progress anti-clockwise forms a solid shape
  • A closed polygon with points progressing clockwise forms a hole

So, let's construct some data and plot:

library(ggplot2)

ids <- letters[1:2]

# IDs and values to use for fill colour
values <- data.frame(
  id = ids,
  value = c(4,5)
)

# Polygon position
positions <- data.frame(
  id = rep(ids, each = 10),
  #     shape      hole         shape        hole
  x = c(1,4,4,1,1, 2,2,3,3,2,   5,10,10,5,5, 6,6,9,9,6),
  y = c(1,1,4,4,1, 2,3,3,2,2,   5,5,10,10,5, 6,9,9,6,6)
)

# Merge positions and values
datapoly <- merge(values, positions, by=c("id"))

ggplot(datapoly, aes(x=x, y=y)) + 
  geom_polygon(aes(group=id, fill=factor(value))) +
  scale_fill_discrete("Key")



来源:https://stackoverflow.com/questions/12033560/use-ggplot-to-plot-polygon-with-holes-in-a-city-map

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