17

我正在尝试制作一个带有两个表示形状和颜色的图例(下例中的“类型”和“组织”)的地图,并插入图例。我可以放置图例,但我希望它们左对齐,以便它们的左边缘对齐。除了相对于彼此居中之外,我无法使它们成为任何东西:

require(ggplot2)
require(ggmap)
require(grid)
require(mapproj)

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 = 'osm')

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)

ggmap(osmMap) + points + legend

在此处输入图像描述

4

1 回答 1

21

这个选项现在在 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)

这不取决于TypeOrg。然而,仅仅拥有两个以上的传说是不够的。此外,如果您进行了一些更改以更改 grobs(图形对象)列表,您可能需要更改图例grobs[[8]]grobs[[i]]位置i,请参阅gtable$grobs并查找TableGrob (5 x 3) "guide-box": 2 grobs. 在此处输入图像描述

编辑: 1.自动检测哪个grob是图例表,即修改绘图的其他部分后无需更改任何内容。2. 更改了宽度差异的计算,现在代码应该在有任何两个图例时都可以工作,即在更复杂的情况下也是如此,例如:

在此处输入图像描述

于 2012-11-18T03:31:46.250 回答