图片应该很好地说明了我想要实现的目标。理想情况下,生成的颜色条将保持连续性,即应该基于连续而不是离散的美学,或者至少非常接近于表现得像它。
这也意味着,不仅仅是将离散填充的图例键靠得足够近的简单方法。
是的,我可以创建一个假的 legend,但我想要一个在图例绘图级别进行修改的解决方案。
我也会很高兴有趣的网格技巧!
library(ggplot2)
ggplot(iris, aes(Sepal.Length, y = Sepal.Width, fill = Petal.Length))+
geom_point(shape = 21) +
scale_fill_continuous() +
guides(fill = guide_colorbar(ticks.colour = "black"))
Run Code Online (Sandbox Code Playgroud)
那是photoshopped,道歉!我不想创建箭头,只是使用分隔符而不是刻度的连续比例

最终目标是重现此线程中最初提出的颜色条

然而,这不是关于创建离散梯度条,这只是关于分隔符!
离散渐变栏是没有问题的,也有已经在那里的解决方案(例如,/sf/answers/4378108381/,/sf/answers/4378973441/,https://开头stackoverflow.com/a/50540633/7941188 )
肯定有一个快速的网格黑客 Tjebo,但它可能需要一些工作才能使其健壮(按名称而不是按数字索引):
library(ggplot2)
library(grid)
p <- ggplot(iris, aes(Sepal.Length, y = Sepal.Width, fill = Petal.Length))+
geom_point(shape = 21) +
scale_fill_continuous() +
guides(fill = guide_colorbar(ticks.colour = "black"))
gt <- ggplot_gtable(ggplot_build(p))
x1 <- gt$grobs[[which(gt$layout$name == "guide-box")]]$grobs[[1]]$grobs[[5]]$x1
x1[1:7] <- x1[8:14]
gt$grobs[[which(gt$layout$name == "guide-box")]]$grobs[[1]]$grobs[[5]]$x1 <- x1
grid.newpage()
grid.draw(gt)
Run Code Online (Sandbox Code Playgroud)

由reprex 包(v0.3.0)于 2020 年 6 月 24 日创建
ggplot v3.3.0 中引入的可扩展指南系统肯定有一个选项。请参阅下面的示例:
library(ggplot2)
guide_longticks <- function(...) {
guide <- guide_colorbar(...)
class(guide) <- c("guide", "guide_longticks", "colorbar")
guide
}
guide_gengrob.guide_longticks <- function(guide, theme) {
dir <- guide$direction
guide <- NextMethod()
is_ticks <- grep("^ticks$", guide$layout$name)
ticks <- guide$grobs[is_ticks][[1]]
if (dir == "vertical") {
ticks$x1 <- rep(tail(ticks$x1, 1), length(ticks$x1))
} else {
ticks$y1 <- rep(tail(ticks$y1, 1), length(ticks$y1))
}
guide$grobs[[is_ticks]] <- ticks
guide
}
ggplot(iris, aes(Sepal.Length, y = Sepal.Width, fill = Petal.Length))+
geom_point(shape = 21) +
scale_fill_continuous() +
guides(fill = guide_longticks(ticks = TRUE, ticks.colour = "black"))
Run Code Online (Sandbox Code Playgroud)

由reprex 包(v0.3.0)于 2020 年 6 月 24 日创建
编辑:
如果您想在刻度之间使用纯色,也可以试试这个替代构造函数:
guide_longticks <- function(...) {
guide <- guide_colorsteps(...)
class(guide) <- c("guide", "guide_longticks", "colorsteps", "colorbar")
guide
}
Run Code Online (Sandbox Code Playgroud)
编辑2:
如果您想要更清晰的矢量文件,以下 gengrob 函数还将删除较小的刻度。不过,它有点假设它们是滴答声的后半部分:
guide_gengrob.guide_longticks <- function(guide, theme) {
dir <- guide$direction
guide <- NextMethod()
is_ticks <- grep("^ticks$", guide$layout$name)
ticks <- guide$grobs[is_ticks][[1]]
n <- length(ticks$x0)
if (dir == "vertical") {
ticks$x0 <- head(ticks$x0, n/2)
ticks$x1 <- rep(tail(ticks$x1, 1), n/2)
} else {
ticks$y0 <- head(ticks$y0, n/2)
ticks$y1 <- rep(tail(ticks$y1, 1), n/2)
}
guide$grobs[[is_ticks]] <- ticks
guide
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
375 次 |
| 最近记录: |