Search code examples
rplotggplot2geom-bar

Highlight every nth bar using geom_bar()


I'm trying to highlight every bar which is a multiple of, say, 5. However, I get improper sizing of the bars when there are any more than one highlighted bar.

Here is sample code to reproduce the error:

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)))

enter image description here

To clarify, this is the desired result: enter image description here

Passing a vector produces a similar error.

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

enter image description here

Both of these methods produce the following error message:

position_stack requires non-overlapping x intervals 

Googling this error leads me to a discussion on formatting for POSIXct dates and requires writing a boolean mask by hand, which is not applicable to this use case.

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

Does anyone have a remedy for this? I'm not able to edit the chart by hand as I have for the desired example here.


Solution

  • (1) Use variable names in aes, not the name of your entire data frame (thus the warning you didn't post). (2) Use an explicit group. (3) Use position = "identity" (default is "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")
    

    enter image description here