使用交互和指南修改ggplot2中的图例
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用交互和指南修改ggplot2中的图例相关的知识,希望对你有一定的参考价值。
df <- data.frame(Depth = c(1, 2, 3, 4, 5, 6, 7, 8),
Var1 = as.factor(c(rep("A", 4), rep("B", 4))),
Var2 = as.factor(c(rep(c("C", "D"), 4))),
Value = runif(8))
g <- ggplot(df, aes(Depth, Value, col = Var1, shape = Var2, lty = Var2))+
geom_path(aes(group = interaction(Var1, Var2)), size = 0.5) +
geom_point(aes(group = interaction(Var1, Var2)), size = 1)+
scale_shape_manual(values = c(16, 5))+
ylab("Depth [cmbsf]")
g + guides(colour = guide_legend(override.aes = list(shape = 15, size = 4, linetype = 0)),
shape = guide_legend(override.aes = list(size = 4)))
我想修改Var2
的图例。我想只增加形状的大小,而不是线条。不幸的是,形状指南中的size
参数也适用于线型。
如果我添加另一个linetype指南:
g + guides(colour = guide_legend(override.aes = list(shape = 15, size = 4, linetype = 0)),
shape = guide_legend(override.aes = list(size = 4)),
lty = guide_legend(override.aes = list(size=1)))
我明白了:
Warning message: In guide_merge.legend(init, x[[i]]) : Duplicated override.aes is ignored.
如何解开用于图例的指南?
答案
可能有点矫枉过正,但我们可以创建geom_path()
的替代方案,其图例密钥大小硬编码为0.5:
ggplot(df, aes(Depth, Value, col = Var1, shape = Var2, lty = Var2)) +
geom_path2(aes(group = interaction(Var1, Var2)), size = 0.5) +
geom_point(aes(group = interaction(Var1, Var2)), size = 1) +
scale_shape_manual(values = c(16, 5)) +
ylab("Depth [cmbsf]") +
guides(colour = guide_legend(override.aes = list(shape = 15, size = 4, linetype = 0)),
shape = guide_legend(override.aes = list(size = 4)))
geom_path2()
所需的代码:
library(grid)
# Create new ggproto object that inherits from GeomPath,
# except for its draw_key function
GeomPath2 <- ggproto("GeomPath2",
GeomPath,
draw_key = function (data, params, size) {
data$linetype[is.na(data$linetype)] <- 0
segmentsGrob(0.1, 0.5, 0.9, 0.5,
gp = gpar(col = alpha(data$colour, data$alpha),
lwd = 0.5 * .pt, # originally lwd = data$size * .pt
lty = data$linetype,
lineend = "butt"),
arrow = params$arrow)
})
# define geom_path2 to be exactly the same as geom_path, except that
# it uses Geom = GeomPath2 instead of Geom = GeomPath
geom_path2 <- function (mapping = NULL, data = NULL, stat = "identity", position = "identity",
..., lineend = "butt", linejoin = "round", linemitre = 10,
arrow = NULL, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE) {
layer(data = data, mapping = mapping, stat = stat,
geom = GeomPath2, # originally GeomPath
position = position, show.legend = show.legend, inherit.aes = inherit.aes,
params = list(lineend = lineend, linejoin = linejoin,
linemitre = linemitre, arrow = arrow, na.rm = na.rm,
...))
}
以上是关于使用交互和指南修改ggplot2中的图例的主要内容,如果未能解决你的问题,请参考以下文章