Reputation: 129
I'm trying to create a faceted map with two layers using ggplot. One is from a data frame containing lat/lon coordinates, created from a CSV:
head(poijoin)
NAME LAT LNG level1
ATM Bank Of America ATM @ WHC 38.92825 -77.01517 ShopService
ATM Bank Of America ATM 38.90577 -77.03654 ShopService
ATM Bank of America 38.91512 -77.02184 ShopService
ATM USAA ATM @CVS 38.91343 -77.03590 ShopService
ATM Bank of America ATM 38.95511 -77.02473 ShopService
The other one is coming from a street network shape file, turned into a dataframe using fortify
:
head(streets_df)
LNG LAT order piece id group
1 -77.02704 38.90253 1 1 0 0.1
2 -77.02704 38.90303 2 1 0 0.1
3 -77.02704 38.90303 3 1 0 0.1
4 -77.02704 38.90304 4 1 0 0.1
5 -77.02704 38.90326 5 1 0 0.1
Plotting them individually works just fine, so does overlaying them:
ggplot() +
geom_point(data = poijoin, aes(x = poijoin$LNG, y = poijoin$LAT)) +
geom_path(data = streets_df, aes(x = LNG, y = LAT, group = group))
(Not very pretty, I know, but I'm trying to stick to the basic parts of the code here.)
I can also facet the points layer without problems:
ggplot() +
geom_point(data = poijoin, aes(x = poijoin$LNG, y = poijoin$LAT)) +
facet_wrap(~ poijoin$level1, nrow=3)
However, if I want to add the streets as a base map to each facet, I'm stuck. This:
ggplot() +
geom_point(data = poijoin, aes(x = poijoin$LNG, y = poijoin$LAT, color = poijoin$level1)) +
geom_path(data = streets_df, aes(x = LNG, y = LAT, group = group)) +
facet_wrap(~ poijoin$level1, nrow=3)
Gives me:
Error in `$<-.data.frame`(`*tmp*`, "PANEL", value = c(8L, 8L, 8L, 8L, :
replacement has 20983 rows, data has 200205
I'm sure the error comes up because the two data frames have a different number of elements (20983 points and 200205 streets), but I still don't get what I'm doing wrong. Any pointers appreciated!
Upvotes: 1
Views: 2419
Reputation: 78832
Let's make a reproducible example:
library(hrbrthemes)
library(tidyverse)
Get a map:
st_map <- map_data("state")
Make some points with 3 groups:
set.seed(2017-12-19)
data_frame(
lat = sample(st_map$lat, 30),
lng = sample(st_map$long, 30),
level = rep(c("A", "B", "C"), 10)
) -> points_df
ggplot() +
geom_path(data=st_map, aes(long, lat, group=group), size=0.25) + # basemap
geom_point(data=points_df, aes(lng, lat, color=level)) + # add our points layer
coord_map("polyconic") + # for funsies
facet_wrap(~level) + # NEVER use a fully qualified column unless you know what you're doing
labs(x=NULL, y=NULL) +
theme_ipsum(grid="") +
theme(axis.text=element_blank()) +
theme(legend.position="none")
ggplot2 will apply the basemap across facets and then apply the faceting to any other layers with a level
category.
Upvotes: 3