gpt4 book ai didi

r - ggmap/ggplot2 中多个图例的对齐方式

转载 作者:行者123 更新时间:2023-12-03 14:05:00 24 4
gpt4 key购买 nike

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

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

enter image description here

最佳答案

这个选项现在在 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 .
enter image description here

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

enter image description here

关于r - ggmap/ggplot2 中多个图例的对齐方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13426470/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com