0

I have been using this as template, but could not make it. Changing colour schemes between facets

df <- data.frame(var1 = factor(rep(c('A','B','C'), 12)),
                 var2 = factor(rep(c("high", "middle", "low"), each = 12)), 
                 var3 = factor(rep(c('X','X','X','Z','Z','Z'), 6)), 
                 value = sample(0:100, 36, rep = TRUE))

All I want is that the legend of var2 appears as in the first figure, including the grey scales.

ggplot(df) +
  geom_bar(aes(x = var3, y = value, 
               fill = var1
               , alpha = var2 ), 
           stat = "identity") + 
  facet_wrap(~var1) +
  scale_alpha_discrete(range = c(0.4,1)) +
  scale_fill_brewer(palette = "Set1"
                    , name = "var1")

ggplot(df, aes(x = factor(var3), y = value, 
               fill = factor(var1)
               , alpha = var2 ), 
       stat = "identity") +
  geom_boxplot(outlier.size=0) + 
  geom_point(size=0.5,position=position_jitterdodge(0.2))  +
  facet_wrap(~var1) +
  scale_alpha_discrete(range = c(1,0.1)) +
  scale_fill_brewer(palette = "Set1"
                    , name = "number 3")

enter image description here

enter image description here

stefan
  • 90,330
  • 6
  • 25
  • 51
SDahm
  • 474
  • 2
  • 9
  • 21

1 Answers1

1

To get the same legend as in the barchart you first have to switch the symbol used for the box plots which can be set via the key_glyph argument of the geom, e.g. setting key_glyph="rect" in geom_boxplot will give you filled rectangles. Note: draw_key_rect is not 100% the same as the key_glyph used for geom_bar and geom_col.

Additionally we have to set the fill color used for the alpha legend. Have no clue why this happens, but it looks like a very light grey is used in case of the box plots. Hence, I have set the fill color to a dark grey via the override.aes argument of guide_legend. Note that this will still not result in 100% the same shades as for the barchart.

Finally, I dropped the geom_point from the legend using show.legend=FALSE.

library(ggplot2)

ggplot(
  df,
  aes(
    x = var3,
    y = value,
    fill = var1
  )
) +
  geom_boxplot(
    aes(alpha = var2),
    outlier.size = 0,
    key_glyph = "rect"
  ) +
  geom_point(
    size = 0.5, position = position_jitterdodge(0.2),
    show.legend = FALSE
  ) +
  facet_wrap(~var1) +
  scale_alpha_discrete(range = c(0.4, 1)) +
  scale_fill_brewer(
    palette = "Set1",
    name = "number 3"
  ) +
  guides(
    alpha = guide_legend(
      override.aes = list(fill = "grey20")
    )
  )

enter image description here

stefan
  • 90,330
  • 6
  • 25
  • 51