这个选项现在在 ggplot2 0.9.3.1 中可用,使用
ggmap(osmMap) + points + legend + theme(legend.box.just = "left")
旧的手动解决方案:
这是一个解决方案:
require(gtable)
require(ggplot2)
require(ggmap)
require(grid)
require(mapproj)
# Original data
data <- data.frame(Org=rep(c("ABCDEFG","HIJKLMNOP","QRSTUVWX"),4),
Type=rep(c("Y","Z"),6), Lat=runif(12,48,54.5),
Long=runif(12,-133.5,-122.5))
osmMap <- get_map(location=c(-134,47.5,-122,55), source = 'google')
points <- geom_jitter(data=data, aes(Long, Lat, shape=Type, colour=Org))
legend <- theme(legend.justification=c(0,0), legend.position=c(0,0),
legend.margin=unit(0,"lines"), legend.box="vertical",
legend.key.size=unit(1,"lines"), legend.text.align=0,
legend.title.align=0)
# Data transformation
p <- ggmap(osmMap) + points + legend
data <- ggplot_build(p)
gtable <- ggplot_gtable(data)
# Determining index of legends table
lbox <- which(sapply(gtable$grobs, paste) == "gtable[guide-box]")
# Each legend has several parts, wdth contains total widths for each legend
wdth <- with(gtable$grobs[[lbox]], c(sum(as.vector(grobs[[1]]$widths)),
sum(as.vector(grobs[[2]]$widths))))
# Determining narrower legend
id <- which.min(wdth)
# Adding a new empty column of abs(diff(wdth)) mm width on the right of
# the smaller legend box
gtable$grobs[[lbox]]$grobs[[id]] <- gtable_add_cols(
gtable$grobs[[lbox]]$grobs[[id]],
unit(abs(diff(wdth)), "mm"))
# Plotting
grid.draw(gtable)
这不取决于Type
或Org
。然而,仅仅拥有两个以上的传说是不够的。此外,如果您进行了一些更改以更改 grobs(图形对象)列表,您可能需要更改图例grobs[[8]]
的grobs[[i]]
位置i
,请参阅gtable$grobs
并查找TableGrob (5 x 3) "guide-box": 2 grobs
.
编辑: 1.自动检测哪个grob是图例表,即修改绘图的其他部分后无需更改任何内容。2. 更改了宽度差异的计算,现在代码应该在有任何两个图例时都可以工作,即在更复杂的情况下也是如此,例如: