提问人:Riccardo 提问时间:10/26/2023 最后编辑:Riccardo 更新时间:10/27/2023 访问量:32
跟进“如何在 R 中将三角形添加到 ggplot2 颜色条以指示越界值?
follow up on 'How can I add triangles to a ggplot2 colorbar in R to indicate out of bound values?'
问:
在这个问题(https://stackoverflow.com/questions/68440366)中,提出了垂直色条的解决方案。我想知道从那时起是否已经开发出更通用的解决方案或软件包,也可以应用于水平色条。
我试图将建议的解决方案应用于水平颜色条,但它不起作用。我也试图操纵参数,但我真的不知道它们是如何工作的。
编辑:我按照teunbrand在前面提到的问题(https://stackoverflow.com/questions/68440366)中提出的解决方案解决了问题,并修改了代码如下:
library(ggplot2)
library(gtable)
library(grid)
my_triangle_colourbar <- function(...) {
guide <- guide_colourbar(...)
class(guide) <- c("my_triangle_colourbar", class(guide))
guide
}
guide_gengrob.my_triangle_colourbar <- function(...) {
# First draw normal colourbar
guide <- NextMethod()
# Extract bar / colours
is_bar <- grep("^bar$", guide$layout$name)
bar <- guide$grobs[[is_bar]]
extremes <- c(bar$raster[1], bar$raster[length(bar$raster)])
# Extract size
width <- guide$widths[guide$layout$l[is_bar]]
height <- guide$heights[guide$layout$t[is_bar]]
short <- min(convertUnit(width, "cm", valueOnly = TRUE),
convertUnit(height, "cm", valueOnly = TRUE))
# Make space for triangles
guide <- gtable_add_cols(guide, unit(short, "cm"),
guide$layout$l[is_bar] - 1)
guide <- gtable_add_cols(guide, unit(short, "cm"),
guide$layout$l[is_bar])
# Draw triangles
left <- polygonGrob(
x = unit(c(0, 1, 1), "npc"),
y = unit(c(.5, 0, 1), "npc"),
gp = gpar(fill = extremes[1], col = NA)
)
right <- polygonGrob(
x = unit(c(0, 0, 1), "npc"),
y = unit(c(0, 1, .5), "npc"),
gp = gpar(fill = extremes[2], col = NA)
)
# Add triangles to guide
guide <- gtable_add_grob(
guide, left,
t = guide$layout$t[is_bar],
l = guide$layout$l[is_bar] - 1
)
guide <- gtable_add_grob(
guide, right,
t = guide$layout$t[is_bar],
l = guide$layout$l[is_bar] + 1
)
return(guide)
}
更准确地说,我修改了“为三角形腾出空间”部分,在条形图前后添加列,并根据需要设计多边形。它似乎有效,但实际上我真的不知道我做了什么,以及是否有另一种更优雅的方法可以做到这一点。下面是一个基本示例:
df<-data.frame(x = c(1:10), y = c(1:10), z = seq(1,20,2))
ggplot(df) +
geom_point(mapping = aes(x = x, y = y, color = z)) +
scale_color_viridis_c(limits = c(1,10), oob = scales::squish,
guide = my_triangle_colourbar()) +
theme(legend.position = 'bottom')
答: 暂无答案
评论