我更改了您的一些数据设置以简化示例。
library(maps)
library(dplyr)
library(ggplot2)
set.seed(123)
# randomly assign 2 variables to each state
mappingData <- data.frame(state = tolower(rownames(USArrests)),
iceCream = (sample(c("No", "Yes"), 50, replace=T)),
hotDogs = (sample(c("No", "Yes"), 50, replace=T))) %>%
mutate(indicator = interaction(iceCream, hotDogs, sep = ":"))
mappingData
state iceCream hotDogs indicator
1 alabama No No No:No
2 alaska Yes No Yes:No
3 arizona No Yes No:Yes
4 arkansas Yes No Yes:No
...
states_map <- map_data("state")
从数据生成独立的图例
legend_ic.hd <- ggplot(mappingData, aes(iceCream, hotDogs, fill = indicator)) +
geom_tile(show.legend = F) +
scale_x_discrete("Ice cream?", expand = c(0,0)) +
scale_y_discrete("Hot dogs?", expand = c(0,0)) +
theme_minimal() +
theme(axis.text.y = element_text(angle = 90, hjust = 0.5)) +
coord_equal()
legend_ic.hd
然后将其用作原始地图中的自定义注释
ggplot(mappingData, aes(map_id = state)) +
geom_map(aes(fill = indicator), map = states_map, show.legend = F) +
expand_limits(x = states_map$long, y = states_map$lat) +
coord_quickmap() +
annotation_custom(grob = ggplotGrob(legend_ic.hd),
xmin = -79, xmax = Inf,
ymin = -Inf, ymax = 33)
您必须手动调整注释的位置,或者:
Use gridExtra
(or cowplot
):
plot_ic.hd <- ggplot(mappingData, aes(map_id = state)) +
geom_map(aes(fill = indicator), map = states_map, show.legend = F) +
expand_limits(x = states_map$long, y = states_map$lat) +
coord_quickmap()
gridExtra::grid.arrange(grobs = list(plot_ic.hd, legend_ic.hd),
ncol = 2, widths = c(1,0.33))