在ggplot2 guide_colorsteps()中为特定的分隔符添加长刻度?

q9yhzks0  于 2023-11-14  发布在  其他
关注(0)|答案(1)|浏览(121)

下面是一个例子:

ggplot(faithfuld, aes(waiting, eruptions, z = density)) + 
  geom_contour_filled() +
  guides(fill = guide_colorsteps()) +
  geom_contour(color = "black", breaks = c(0.03))

字符串
x1c 0d1x我想在色标上的特定断点(这里是0.03)上添加一个长刻度以帮助解释,就像黑色轮廓线一样。我在Continuous color bar with separators instead of ticks中找到了@teunbrand提出的一个接近解决方案:

guide_longticks <- function(...) {
  guide <- guide_colorsteps(...)
  class(guide) <- c("guide", "guide_longticks", "colorsteps", "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]]
  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
}

ggplot(faithfuld, aes(waiting, eruptions, z = density)) + 
  geom_contour_filled() +
  guides(fill = guide_longticks(ticks = TRUE, ticks.colour = "black")) +
  geom_contour(color = "black", breaks = c(0.03))


然而,这个解决方案将tick添加到所有break中,但我只需要在0.03处添加一个tick。
我很欣赏保持geom_contour_filled()和guide_colorsteps()的答案!

tktrz96b

tktrz96b1#

我可以提供以下适合特定情况的解决方案:

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)
    ticks$x1[-6] <- unit(0,"cm") # ---- Added this line ----
  } else {
    ticks$y0 <- head(ticks$y0, n/2)
    ticks$y1 <- rep(tail(ticks$y1, 1), n/2)
  }
  
  guide$grobs[[is_ticks]] <- ticks
  guide
}

字符串


的数据

相关问题