Reputation: 1041
I am reading the book ggplot2 written by Hadley Wickham, and following the codes. However, the USAboundaries package is not working in the way as it is shown in the book. In the book, the codes work like this:
library(USAboundaries)
c18 <- us_boundaries(as.Date("1820-01-01"))
c18df <- fortify(c18)
#> Regions defined for each Polygons
head(c18df)
#> long lat order hole piece id group
#> 1 -87.6 35 1 FALSE 1 4 4.1
#> 2 -87.6 35 2 FALSE 1 4 4.1
#> 3 -87.6 35 3 FALSE 1 4 4.1
#> 4 -87.6 35 4 FALSE 1 4 4.1
#> 5 -87.5 35 5 FALSE 1 4 4.1
#> 6 -87.3 35 6 FALSE 1 4 4.1
ggplot(c18df, aes(long, lat)) +
geom_polygon(aes(group = group), colour = "grey50", fill = NA) +
coord_quickmap()
However, when I am running the same codes in RStudio, the data frame is totally different: The long and lat values are vectorized in nested list such as:
geometry
list(list(c(-88.0746219415898, -88.3133290074677, ...)))
list(list(c(-96.7247616421399, -96.0010234528651, ...)))
...
...
... means there are many many values there.
Therefore, the ggplot codes above doesn't work because the data frame doesn't have long and lat. Since there are no long and lat variable(columns), how should I create a long and lat from this data? Maybe you could install this package and try run it to see what's going on.
Thank you very much for your help!
Upvotes: 2
Views: 91
Reputation: 39154
I am not familiar with the fortify
function, but notice that the output of the us_boundaries
should be an sf
object, and the way to specify the date in us_boundaries
does not require as.Date
(see the example in ?us_boundaries
).
Since c18
is an sf
object, you don't have to use geom_polygon
. As a result, I removed the as.Date
from your code, and plot the c18
using ggplot
and geom_sf
.
library(USAboundaries)
library(ggplot2)
library(sf)
c18 <- us_boundaries("1820-01-01")
ggplot() +
geom_sf(data = c18)
See this link to learn more about plotting the sf
object: https://cran.r-project.org/web/packages/sf/vignettes/sf5.html#ggplot2
UPDATE
I did more research on this issue. The fortify
function can convert an Spatial Polygon Data Frame to a data frame. It looks like the original version of us_boundaries
returns a Spatial Polygon Data Frame, so it is necessary to convert it to a data frame with the fortify
function.
Below I first convert the sf
object to a Spatial Polygon Data Frame, and then use the fortify
function to reproduce the original process. Now we can plot c18df
with geom_polygon
.
library(USAboundaries)
library(ggplot2)
library(sf)
c18 <- us_boundaries("1820-01-01")
c18spdf <- as(c18, "Spatial")
c18df <- fortify(c18spdf)
ggplot(c18df, aes(long, lat)) +
geom_polygon(aes(group = group), colour = "grey50", fill = NA) +
coord_quickmap()
Upvotes: 2