我偶然发现这个奇怪的行为与ggplot2s传说的排序,只是无法弄清楚传说的自动放置背后的逻辑是什么:
我的目标:在具有多个音阶的情节中,我想以不同于自动音阶的顺序排列它们。但我无法在opts()或指南()中找到命令为我这样做。而且要明确一点:我不想改变传说中的项目,这很好,但是安排了多个完整的传说。
所以首先我假设它们按类型排序,即比例,颜色等。但事实并非如此,它们的位置会发生变化(见下文)。
按字母顺序排列?否。
library(ggplot2) ## v0.9
## Scale_colour on top
qplot(data = mpg,x = displ, y = cty, size = hwy, colour = class) +
scale_size(name = "A") + scale_colour_discrete(name = "B")
## Reverse names --> scale_colour on bottom
qplot(data = mpg,x = displ, y = cty, size = hwy, colour = class) +
scale_size(name = "B") + scale_colour_discrete(name = "A")
## Change name B to C --> scale_colour on bottom
qplot(data = mpg,x = displ, y = cty, size = hwy, colour = class) +
scale_size(name = "C") + scale_colour_discrete(name = "A")
## Change name B to D --> scale_colour on top
qplot(data = mpg,x = displ, y = cty, size = hwy, colour = class) +
scale_size(name = "D") + scale_colour_discrete(name = "A")
scale_colour的更多位置(用于交换的scale_size名称)
它继续出现在底部的顶部。
阶乘订单?否。
## From top to bottom: C - B - A
fname <- factor(c("A","B","C"), levels = c("A","B","C"))
qplot(data = mpg,x = displ, y = cty, size = hwy, colour = class, alpha = cyl) +
scale_size(name = fname[1]) + scale_colour_discrete(name = fname[2]) + scale_alpha(name=fname[3])
## From top to bottom: B - C - A
fname <- factor(c("A","B","C"), levels = c("C","B","A"))
qplot(data = mpg,x = displ, y = cty, size = hwy, colour = class, alpha = cyl) +
scale_size(name = fname[1]) + scale_colour_discrete(name = fname[2]) + scale_alpha(name=fname[3])
## From top to bottom: B - C - A
fname <- factor(c("A","B","C"), levels = c("B","C","A"))
qplot(data = mpg,x = displ, y = cty, size = hwy, colour = class, alpha = cyl)+
scale_size(name = fname[1]) + scale_colour_discrete(name = fname[2]) + scale_alpha(name=fname[3])
标题长度?不是。 我现在停止使用示例代码,但是那个也产生了与字符长度无关的波动顺序。
有什么想法吗?
答案 0 :(得分:17)
正如我在上面的评论中所提到的,没有办法控制和预测图例框的位置。 我不知道这个问题。谢谢你说明这一点。
也许有些人需要控制图例框,我在这里快速修复:
# run this code before calling ggplot2 function
guides_merge <- function(gdefs) {
gdefs <- lapply(gdefs, function(g) { g$hash <- paste(g$order, g$hash, sep = "z"); g})
tapply(gdefs, sapply(gdefs, function(g)g$hash), function(gs)Reduce(guide_merge, gs))
}
environment(guides_merge) <- environment(ggplot)
assignInNamespace("guides_merge", guides_merge, pos = "package:ggplot2")
然后您可以order
使用guide_legend
参数(以及guide_colorbar
),
# specify the order of the legend.
qplot(data = mpg,x = displ, y = cty, size = hwy, colour = class, alpha = cyl)+
guides(size = guide_legend(order = 1), colour = guide_legend(order = 2), alpha = guide_legend(order = 3))
qplot(data = mpg,x = displ, y = cty, size = hwy, colour = class, alpha = cyl)+
guides(size = guide_legend(order = 3), colour = guide_legend(order = 1), alpha = guide_legend(order = 2))
order
参数应为正整数。传说按顺序排列。
请注意,这是一个快速修复,因此可以在ggplot2的下一个正式版本中更改界面。