I'm trying to build a map in ggplot2
using data from separate data frames.
library(maptools)
xx <- readShapePoly(system.file("shapes/sids.shp", package="maptools")[1], IDvar="FIPSNO", proj4string=CRS("+proj=longlat +ellps=clrk66"))
xx.sub1 <- subset(xx, xx$FIPSNO < 37010)
xx.sub2 <- subset(xx, xx$FIPSNO > 37010)
xx.sub1@data$id <- rownames(xx.sub1@data)
xx.sub1.points <- fortify(xx.sub1, region="id")
xx.sub1.df = plyr::join(xx.sub1.points, xx.sub1@data, by="id")
xx.sub2@data$id <- rownames(xx.sub2@data)
xx.sub2.points <- fortify(xx.sub2, region="id")
xx.sub2.df = plyr::join(xx.sub2.points, xx.sub2@data, by="id")
ggplot(xx.sub2.df) +
aes(long, lat, fill = (SID79/BIR79)*1000, group = group) +
geom_polygon() + geom_path(color="grey80") +
coord_equal() +
scale_fill_gradientn(colours = RColorBrewer::brewer.pal(7, "YlOrBr")) +
geom_polygon(data = xx.sub1.df, fill = "grey50") +
geom_path(data = xx.sub1.df, color="grey80") +
labs(fill = "Mapped value", title = "Title")
Up to this point everything works as expected and I get a nice map:
What I'd like to change however is to add separate legend for data from xx.sub1.df
- since all polygons are just filled with grey I hope it will be one additional entry.
How can I achieve that?
scales
package to see if there's another way – Ben Bolkerdput
of your data, so that one can answer your question with an updated heatmap? I'm guessing that: (1)you use only 2 columns ofxx.sub2
, (2) states appear grey if they are present inxx.sub1
. Hence joining doesn't seem that annoying. You could simply add a factor inxx.sub2
for entries that are inxx.sub1
, and perhaps usescale_fill_manual
to adjust colours in the legend. – G Chalanconmaptools
package, which sI hope allows reproducibility of an example (I believedput
is not needed any longer?). As for points 1 and 2 - all valid options for the toy example. For real scenarios however, datasets are more complex and your solution would be harder to implement. Hence, I'd love to be able to achieve that without the joins, working with 'independent' data frames. – radekgeom_polygon
for both data frames). As far as I know it's not possible in ggplot2, but here is a suggestion: how about using a different annotation (e.g. ageom_text
) to mark the 'grey' regions? It would give you 2 legends, but I understand it might not be that satisfactory. One thing: is it possible that in a real case regions ofxx.sub1.df
would overlap withxx.sub2.df
? – G Chalancon