r - 对齐 ggplot choropleth 的边缘(图例标题各不相同)

标签 r ggplot2 gridextra

我正在尝试使用 this method 对齐 4 个 ggplot choropleth map 的左右边缘。但我无法做到这一点。

原情节:

library(ggplot2); library(gridExtra)
crimes <- data.frame(state = tolower(rownames(USArrests)), USArrests)
states_map <- map_data("state")
plot1 <- ggplot(crimes, aes(map_id = state)) +
    geom_map(aes(fill = Murder), map = states_map) +
    expand_limits(x = states_map$long, y = states_map$lat) + 
    scale_fill_gradient(low="white", high="darkgreen", name="Really Long Name 1")


plot2 <- plot1 + scale_fill_gradient(name="Really Long Name 2 and then some")
plot3 <- plot1 + scale_fill_gradient(name="Short 3") 
plot4 <- plot1 + scale_fill_gradient(name="Really Long Name 4")

grid.arrange(plot1, plot3, plot2, plot4, ncol = 2)

尝试对齐绘图边缘(相同结果):

p1 <- ggplotGrob(plot1)
p2 <- ggplotGrob(plot2)
p3 <- ggplotGrob(plot3)
p4 <- ggplotGrob(plot4)

maxWidth <- grid::unit.pmax(p1$widths[2:3], p2$widths[2:3], p3$widths[2:3], p4$widths[2:3])
p1$widths[2:3] <- as.list(maxWidth)
p2$widths[2:3] <- as.list(maxWidth)
p3$widths[2:3] <- as.list(maxWidth)
p4$widths[2:3] <- as.list(maxWidth)

grid.arrange(p1, p3, p2, p4, ncol = 2) 

enter image description here

PS:假设我需要使用网格排列,并且图例实际上并不是相同的比例,因此 facet_grid 已退出等。

最佳答案

这是一个例子:

library(gtable)
grid.draw(cbind(rbind(p1, p2, size="last"), rbind(p3, p4, size="last"), size = "first"))

enter image description here

<小时/>

已更新

这是一个糟糕的黑客,所以我不建议使用。 也许这在未来行不通。

gt <- cbind(rbind(p1, p2, size="last"), rbind(p3, p4, size="last"), size = "first")
for (i in which(gt$layout$name == "guide-box")) {
  gt$grobs[[i]] <- gt$grobs[[i]]$grobs[[1]]
}
grid.draw(gt)

enter image description here

关于r - 对齐 ggplot choropleth 的边缘(图例标题各不相同),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17462504/

相关文章:

r - 分层考克斯模型的生存

r - 如何使用 R 在 html 中的注释标签内抓取表格?

r - 在 R 中并行处理多个 quant mod 股票代码

从 wrld_simpl 全局 map 中移除南极洲

python - Python 中是否有 gridExtra/cowplot 类型包与 Plotnine 一起使用以对齐子图(即边际分布)

r - 下拉菜单未在 Shiny 的 tabPanel 中扩展

r - 在 ggplot2 上绘制世界地图

r - 将带有 facet_grid 的 ggplot2 对象的标题移到中间

r - grid.arrange 或arrangeGrob 中的主标题具有灰色背景

r-markdown - Rmarkdown : Multiple plots on same page with separate captions