我试图使用 生成一个“令人满意的”图例ggplot2,但令我沮丧的是刻度线的位置(它们位于图例键内)。这是一些代码来说明我的意思。
library(ggplot2)
ggplot(mtcars, aes(x = cyl, y = gear, fill = mpg)) +
geom_tile() +
coord_equal() +
theme(legend.position = 'top')
Run Code Online (Sandbox Code Playgroud)
有没有办法将刻度线放在图例钥匙框之外?就像这个传说一样(看起来他们是用 这样做的ggplot2):
任何建议将不胜感激!
我们可以破解未导出的ggplot2:::guide_gengrob.colorbar函数来模拟这种外观。
跑步
trace(ggplot2:::guide_gengrob.colorbar, edit = TRUE)
Run Code Online (Sandbox Code Playgroud)
并替换以下行(应该在第 26 行左右)
if (guide$raster) {
image <- switch(guide$direction, horizontal = t(guide$bar$colour),
vertical = rev(guide$bar$colour))
grob.bar <- rasterGrob(image = image, width = barwidth,
height = barheight, default.units = "cm", gp = gpar(col = NA),
interpolate = TRUE)
}
Run Code Online (Sandbox Code Playgroud)
和
if (guide$raster) {
image <- switch(guide$direction,
horizontal = with(guide$bar,
rbind(rep("white", length(colour)),
colour,
rep("white", length(colour)))),
vertical = with(guide$bar,
cbind(rep("white", length(colour)),
rev(colour),
rep("white", length(colour)))))
grob.bar <- rasterGrob(image = image, width = barwidth,
height = barheight, default.units = "cm", gp = gpar(col = NA),
interpolate = FALSE)
}
Run Code Online (Sandbox Code Playgroud)
并点击“保存”。
现在下面的代码
p <- ggplot(mtcars, aes(x = cyl, y = gear, fill = mpg)) +
geom_tile() +
coord_equal() +
scale_fill_continuous(guide = guide_colourbar(ticks.colour = "black"))
# works for both horizontal & vertical legends
p + theme(legend.position = 'top')
p + theme(legend.position = 'right')
Run Code Online (Sandbox Code Playgroud)
产生
要在当前 R 会话期间的任何时刻删除效果,请运行
untrace(ggplot2:::guide_gengrob.colorbar)
Run Code Online (Sandbox Code Playgroud)
(注意:此 hack 的效果不会在 R 会话中持续存在,并且每次需要时都需要重复。)
解释
代码中的原始内容image基本上是一个渐变颜色向量,然后用于创建光栅对象。在我们的修改版本中,我们将向量与两个重复的“白色”向量(水平或垂直)夹在中间,以便可见的渐变图例变得更窄,并且刻度不再与其重叠。
然后,我们在光栅格罗布的定义中更改interpolate = TRUE为interpolate = FALSE,以便我们获得从白色到渐变条的急剧过渡,反之亦然。
最后,在 ggplot 代码中将刻度线颜色设置为“黑色”,以便实际上可以在白色背景下看到刻度线。