使用 geom_bar() 突出显示第 n 个柱

Highlight every nth bar using geom_bar()

我试图突出显示每一个是 5 的倍数的条。但是,当有超过一个突出显示的条时,我得到的条的大小不正确。

这里是重现错误的示例代码:

library(ggplot2)

smpl <- data.frame(sample(1:31, 1000, replace = T))

p <- ggplot(data = smpl, aes(x = smpl)) +
    geom_bar()

p +
  geom_bar(aes(fill = (smpl %% 5 == 0)))

澄清一下,这是期望的结果:

传递向量会产生类似的错误。

p +
  geom_bar(aes(fill = (smpl == c(5, 10, 15, 20, 25, 30))))

这两种方法都会产生以下错误消息:

position_stack requires non-overlapping x intervals 

谷歌搜索这个错误让我讨论了 POSIXct 日期的格式,并且需要手动编写一个布尔掩码,这不适用于这个用例。

然而,it works fine if I try to just highlight a single value.

有人有办法解决这个问题吗?我无法像此处所需示例那样手动编辑图表。

(1) 在 aes 中使用变量名称,而不是整个数据框的名称(因此警告您没有 post)。 (2) 使用明确的group。 (3) 使用position = "identity"(默认为"stack"

# create the data with a proper variable name
smpl <- data.frame(x = sample(1:31, 1000, replace = T))

ggplot(data = smpl, aes(x = x)) +
   geom_bar(aes(fill = (x %% 5 == 0), group = x), position = "identity")