您的问题是您需要提供fortify
一个实际存在的列。如果您str(lon.shape)
从下面的示例代码中键入,您将看到没有region
列:
> str(lon.shape)
Formal class 'SpatialPolygonsDataFrame' [package "sp"] with 5 slots
..@ data :'data.frame': 1 obs. of 7 variables:
.. ..$ ons_label: chr "00AA"
.. ..$ name : chr "City of London"
.. ..$ label : chr "02AA"
.. ..$ X_max : num 533843
.. ..$ y_max : num 182198
.. ..$ X_min : num 0
.. ..$ y_min : num 0
..@ polygons :List of 1
.. ..$ :Formal class 'Polygons' [package "sp"] with 5 slots
.. .. .. ..@ Polygons :List of 1
.. .. .. .. ..$ :Formal class 'Polygon' [package "sp"] with 5 slots
.. .. .. .. .. .. ..@ labpt : num [1:2] 532464 181220
.. .. .. .. .. .. ..@ area : num 3151465
.. .. .. .. .. .. ..@ hole : logi FALSE
.. .. .. .. .. .. ..@ ringDir: int 1
.. .. .. .. .. .. ..@ coords : num [1:771, 1:2] 531027 531029 531036 531074 531107 ...
.. .. .. ..@ plotOrder: int 1
.. .. .. ..@ labpt : num [1:2] 532464 181220
.. .. .. ..@ ID : chr "0"
.. .. .. ..@ area : num 3151465
..@ plotOrder : int 1
..@ bbox : num [1:2, 1:2] 530967 180404 533843 182198
.. ..- attr(*, "dimnames")=List of 2
.. .. ..$ : chr [1:2] "x" "y"
.. .. ..$ : chr [1:2] "min" "max"
..@ proj4string:Formal class 'CRS' [package "sp"] with 1 slots
.. .. ..@ projargs: chr "+proj=tmerc +lat_0=49 +lon_0=-2 +k=0.9996012717 +x_0=400000 +y_0=-100000 +ellps=airy +units=m +no_defs"
相反,请尝试使用name
,如下所示:
lon.df <- fortify(lon.shape, region = "name")
产生这个数据框:
> head(lon.df)
long lat order hole piece group id
1 531026.9 181611.1 1 FALSE 1 City of London.1 City of London
2 531028.5 181611.2 2 FALSE 1 City of London.1 City of London
3 531036.1 181611.5 3 FALSE 1 City of London.1 City of London
4 531074.0 181610.3 4 FALSE 1 City of London.1 City of London
5 531107.0 181609.3 5 FALSE 1 City of London.1 City of London
6 531117.1 181608.9 6 FALSE 1 City of London.1 City of London
这是一种解决方法,从开始到结束:
library(rgdal)
library(ggplot2)
library(rgeos)
shape.dir <- "c:/test/london" # use your directory name here
lon.shape <- readOGR(shape.dir, layer = "lond_city")
lon.df <- fortify(lon.shape, region = "name")
ggplot(lon.df, aes(x = long, y = lat, group = group)) +
geom_polygon(colour = "black", fill = "grey80", size = 1) +
theme()
...导致以下结果: