我想使用 ggplot2
绘制绘图,其中一些填充值被剪裁,即高于或低于色标限制的值显示为最小/最大颜色。我可以让它像这样工作,使用 limit
和 oob
(越界)的组合:
library(ggplot2)
library(scales)
ggplot() + ... + scale_fill_viridis(na.value="white", limit=c(0, 10), oob=squish)
但是颜色栏中没有信息表明存在超出限制的值。 我怎样才能在 ggplot 中重现这个 matplotlib 示例:https://stackoverflow.com/a/32072348
具体来说,如何获取colorbar末端的三角形?
最佳答案
据我所知,在 ggplot2 中没有实现颜色条三角形末端的包(但如果有,请告诉我!)。但是,我们可以实现自己的。我们需要一个自定义指南的构造函数和一种绘制它的方法。大部分内容已经在 guide_colourbar()
及其类的方法中实现,因此我们需要做的只是标记我们自己的类并扩展 guide_gengrob
方法。下面的代码应该适用于垂直方向的颜色条。您需要了解有关 grid
包和 gtable
包的一些知识才能跟进。
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_rows(guide, unit(short, "cm"),
guide$layout$t[is_bar] - 1)
guide <- gtable_add_rows(guide, unit(short, "cm"),
guide$layout$t[is_bar])
# Draw triangles
top <- polygonGrob(
x = unit(c(0, 0.5, 1), "npc"),
y = unit(c(0, 1, 0), "npc"),
gp = gpar(fill = extremes[1], col = NA)
)
bottom <- polygonGrob(
x = unit(c(0, 0.5, 1), "npc"),
y = unit(c(1, 0, 1), "npc"),
gp = gpar(fill = extremes[2], col = NA)
)
# Add triangles to guide
guide <- gtable_add_grob(
guide, top,
t = guide$layout$t[is_bar] - 1,
l = guide$layout$l[is_bar]
)
guide <- gtable_add_grob(
guide, bottom,
t = guide$layout$t[is_bar] + 1,
l = guide$layout$l[is_bar]
)
return(guide)
}
然后您可以将自定义指南用作比例尺中的指南
参数。
g <- ggplot(mtcars, aes(mpg, wt)) +
geom_point(aes(colour = drat))
g + scale_colour_viridis_c(
limits = c(3, 4), oob = scales::oob_squish,
guide = my_triangle_colourbar()
)
实际上并没有一种自然的方法来对越界值进行不同的着色,但是您可以将极值附近的非常小的切片设为不同的颜色。
g + scale_colour_gradientn(
colours = c("red", scales::viridis_pal()(255), "hotpink"),
limits = c(3, 4), oob = scales::oob_squish,
guide = my_triangle_colourbar()
)
由 reprex package 创建于 2021-07-19 (v1.0.0)
关于r - 如何将三角形添加到 R 中的 ggplot2 颜色条以指示超出范围的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68440366/