Graphics Reference
In-Depth Information
# Look at the structure of the object
str(taiwan_shp)
Formal class 'SpatialPolygonsDataFrame' [package "sp" ] with 5 slots
.. @ data : 'data.frame' : 22 obs. of 11 variables:
.. .. $ ID_0 : int [ 1 : 22 ] 223 223 223 223 223 223 223 223 223 223 ...
.. .. $ ISO : Factor w / 1 level "TWN" : 1 1 1 1 1 1 1 1 1 1 ...
.. .. $ NAME_0 : Factor w / 1 level "Taiwan" : 1 1 1 1 1 1 1 1 1 1 ...
.. .. $ ID_1 : int [ 1 : 22 ] 1 2 3 4 4 4 4 4 4 4 ...
... [lots more stuff]
.. @ proj4string:Formal class 'CRS' [package "sp" ] with 1 slots
.. .. .. @ projargs: chr NA
Converting it to a regular data frame gives the following:
taiwan_map <- fortify(taiwan_shp)
taiwan_map
long lat order hole piece group id
120.2390 22.75155
1 FALSE
1
0.1 0
120.2701 22.74135
2 FALSE
1
0.1 0
120.2996 22.70920
3 FALSE
1
0.1 0
...
120.1340 23.61569 1236 FALSE
3 21.3 21
120.1340 23.61597 1237 FALSE
3 21.3 21
120.1365 23.61597 1238 FALSE
3 21.3 21
It's actually possible to pass the SpatialPolygonsDataFrame object directly to ggplot() ,
which will automatically fortify() it:
# Send the SpatialPolygonsDataFrame directly to ggplot()
ggplot(taiwan_shp, aes(x = long, y = lat, group = group)) + geom_path()
Even though this code is a bit simpler, you may still want to convert it yourself using fortify() .
This will let you more easily inspect the data structure that is sent to ggplot() , or merge the
data frame with another data set.
See Also
The shapefile used in this example is not included in the gcookbook package. It and many other
shapefiles are available for download .
Search WWH ::




Custom Search