0

Suppose I have a plot like this,

library(ggplot2)

p <- ggplot(iris, aes(x=Species, y=Petal.Length)) + 
  geom_violin()
p

What I want is to annotate the right with a color coded bar. Is this possible? I included a hypothetical plot that I drew in.

enter image description here

Ahdee
  • 4,679
  • 4
  • 34
  • 58
  • 1
    Can you add `fill = Species` in `aes` `p <- ggplot(iris, aes(x=Species, y=Petal.Length, fill = Species)) + geom_violin()` – akrun Jul 15 '21 at 23:15
  • 1
    @akrun no because the annotation would be independent of the species, else that would certiantly work. So for example, I need 3-6 to be in brown which will cover both species toward the right. – Ahdee Jul 15 '21 at 23:18
  • One options would be to make use of `patchwork`. See e.g. my answer [here](https://stackoverflow.com/a/62073793/12993861). – stefan Jul 16 '21 at 06:32

1 Answers1

1

The annotate function can do exactly as you indicate. The think to remember is that discrete scales have a continuous scale underneath and that the positions of discrete categories is match(x, sort(unique(x)), so that you bar should start around 3.5 for the iris dataset.

library(ggplot2)

ggplot(iris, aes(Species, y = Petal.Length)) +
  geom_violin() +
  annotate(
    xmin = 3.5, xmax = 3.75,
    ymin = c(-Inf, 3, 6),
    ymax = c(3, 6, Inf),
    geom = "rect",
    fill = c("dodgerblue", "tan", "red")
  )

Created on 2021-07-16 by the reprex package (v1.0.0)

teunbrand
  • 33,645
  • 4
  • 37
  • 63
  • thank you this is perfect! I also realized that this could also be used to increase the number of block annotations and not limited to three as the example above. ```ymin = c(-Inf, 3, 6, 8), ymax = c(3, 6, 8, Inf)``` – Ahdee Jul 16 '21 at 15:57