Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
559 views
in Technique[技术] by (71.8m points)

r - Align edges of ggplot choropleth (legend title varies)

I am attempting to align the left and right edges of 4 ggplot choropleth maps using this method. I am unable to do this though.

Original plot:

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)

Attempt to align plot edges (same result):

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: Assume I need to use grid arrange and the legends are not actually the same scale so facet_grid is out etc.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here is an example:

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

enter image description here


Updated

This is a bad hack so I don't recommend to use. Probably this will not work in future.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...