0

I have a data frame that has the boundaries for several polygons (in this case, US Census Tracts).

I'm trying to plot those with ggmap, but I'm getting an error when I try to zoom in. Since some points in those polygons fall outside the ggmap boundary, they are removed (instead of considered, but not in the plot area), which leads to wrong shapes.

For example, here's the top of the data frame:

> head(tract_df)
       long      lat order  hole piece id group
1 -110.8798 32.24926     1 FALSE     1  0   0.1
2 -110.8798 32.24973     2 FALSE     1  0   0.1
3 -110.8798 32.24988     3 FALSE     1  0   0.1
4 -110.8798 32.25004     4 FALSE     1  0   0.1
5 -110.8798 32.25051     5 FALSE     1  0   0.1
6 -110.8798 32.25058     6 FALSE     1  0   0.1

When I simply plot with ggplot, I can plot those nicely, using the coord_map() function:

ggplot() +
  geom_polygon(data = tract_df, 
               aes(x = long, y = lat, group = group),
               color = "black", 
               size = 0.10, alpha = 0.7) +
  coord_map(xlim = c(-112.68, -111.44), 
            ylim = c(33.18, 33.83))

Correct Map Using ggplot2

However, if I use ggmap, it breaks those borders:

ggmap(phoenix_map) +
  geom_polygon(data = tract_df, 
               aes(x = long, y = lat, group = group),
               color = "black", 
               size = 0.10, alpha = 0.7)

Incorrect Map

If I add coord_map to the ggmap plot, I get a warning, but it works. Is there a correct way of doing this that won't get me the warning?

Leo Barlach
  • 480
  • 3
  • 13
  • There's a few posts that are probably related https://stackoverflow.com/questions/29825458/plotting-shape-files-with-ggmap-clipping-when-shape-file-is-larger-than-ggmap and https://stackoverflow.com/questions/13469566/polygons-nicely-cropping-ggplot2-ggmap-at-different-zoom-levels – camille Sep 13 '19 at 01:53
  • 2
    I'm guessing that ggmap is dropping data that falls outside the bounding box for `phoenix_map`. `ggplot2`s functions `xlim` and `ylim` have this effect and so that may be what's happening in the background. The `xlim` and `ylim` *arguments* to `coord_map` on the other hand should set the extent of the plot without dropping data beyond that extent. With all that in mind, a work around might be to get a basemap with a larger bounding box, then set your map extent with `coord_map(xlim, ylim)`. – Gregory Sep 13 '19 at 03:18

0 Answers0