作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我怎样才能根据这个列联表做到这一点?我不完全确定如何根据我制作的指标表(犯罪)在 R 中创建自定义图例。
R 中的可重现代码:
require(maps)
set.seed(123)
# randomly assign 2 variables to each state
mappingData <- data.frame(state = tolower(rownames(USArrests)),
iceCream = (sample(c("Likes Ice Cream","Doesn't Like Ice Cream"),50, replace=T)),
hotDogs = (sample(c("Likes Hot Dogs","Doesn't Like Hot Dogs"),50, replace=T)))
# create a 'legend' key for an indicator variable
mappingDataDF<-data.frame(
expand.grid(iceCream=c("Likes Ice Cream","Doesn't Like Ice Cream"),
hotDogs=c("Likes Hot Dogs","Doesn't Like Hot Dogs")),
indicator=c("0","1","2","3"))
mappingData<-mappingData %>% inner_join(mappingDataDF)
mappingDatam <- reshape2::melt(mappingData, id = 1)
states_map <- map_data("state")
ggplot(mappingData, aes(map_id = state)) +
geom_map(aes(fill = indicator), map = states_map) +
expand_limits(x = states_map$long, y = states_map$lat)
最佳答案
我更改了您的一些数据设置以简化示例。
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)
gridExtra
(或
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))
关于r - 根据geom_map 或ggplot2 中的列联表(2x2)创建一个独特的图例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46063337/
我是一名优秀的程序员,十分优秀!