I'm trying to create a choropleth map with my own polygons. The polygons tile the entire world but I only want to display the area within the US. What I want is to clip the polygons that go outside of a bounding box covering the US, but what happens when I specify the bounding box as limits is that all polygons that are partly outside the bounding box aren't drawn at all.
I have data that looks like this, specifying rectangles:
lat long rank group
1 36.56792 -80.260138889 1 1
2 37.97319 -80.260138889 1 1
3 37.97319 -78.866805556 1 1
4 36.56792 -78.866805556 1 1
5 -45.00000 -0.008333334 2 2
6 -22.00000 -0.008333334 2 2
7 -22.00000 22.075000000 2 2
8 -45.00000 22.075000000 2 2
9 -44.99500 -67.441666667 3 3
10 -33.60000 -67.441666667 3 3
11 -33.60000 -45.700000000 3 3
12 -44.99500 -45.700000000 3 3
...
I'm using code like this:
library(ggplot2)
library(maps)
tab = read.table("hiergrid.level1.penn-ave.dat", header = TRUE)
data = data.frame(tab)
mapstates = map_data("state")
ggplot(data, aes(long, lat, group=group)) +
geom_polygon(aes(fill=rank)) +
ylim(25,50) +
xlim(-125,-60) +
coord_map(project="polyconic") +
geom_path(data = mapstates, color = "white", size = .75)
I get output like this:
As can be seen, the polygons outside the bounding box aren't drawn at all, but I want them drawn and clipped. Any help?
OK, it looks like this can be fixed by specifying limits to coord_map()
. But I still have to specify xlim
and ylim
:
library(ggplot2)
library(maps)
tab = read.table("hiergrid.level1.penn-ave.dat", header = TRUE)
data = data.frame(tab)
mapstates = map_data("state")
ggplot(data, aes(long, lat, group=group)) +
ylim(0,90) +
xlim(-180,-20) +
geom_polygon(aes(fill=rank)) +
coord_map(project="mercator", ylim=c(24,50), xlim=c(-126,-66)) +
geom_path(data = mapstates, color = "white", size = .75)
Output is like this:
Note, however, if I leave out xlim
and ylim
, or if they're too wide in the X axis, I get very weird output, like this:
I'm not sure why this is happening.