Modify the colors in geom_mosaic() plot

414 Views Asked by At

I want to plot a mosaic plot with ggplot2 and choose the colors manually, i.e, pick the colors for each category (A, B, C, D, E, F) on the y axis. Currently, I can only select the colors for each category on the x axis (X, Y, Z) with the scale_fill_brewer() command.

bd <- data.frame(x = c(120,5,15,5,20,100, 400,15,50,80,45,410, 250,15,75,35,40,250), 
y = rep(c("A", "B", "C", "D", "E", "F"), 3),
         z = c(rep("X",6),rep("Y",6),rep("Z",6)))
bd$weight = bd$x/sum(bd$x)

ggplot(bd) +
  geom_mosaic(aes(x = product(y, z), 
                  fill = z, weight = weight), offset = 0.015) +
  scale_fill_brewer(palette=2) +
  #scale_color_brewer(palette=3) +
  theme_mosaic()
  

Output:

mosaic plot

And I wanted something like in the graphs provided in this answer. This seems really easy, but I can't seem to find the answer. Can someone help?

2

There are 2 best solutions below

1
On BEST ANSWER

Since you mentioned in your OP that you were interested in setting the fill colors manually, here is a way to do that. In @stefan answer you just need to substitute the scale_fill_brewer(palette=2) line for the following:

scale_fill_manual(values = c("A" = "firebrick2",
                             "B" = "royalblue",
                             "C" = "gold2",
                             "D" = "orchid2",
                             "E" = "forestgreen",
                             "F" = "orange2"))

You can consult some predefined color names in ggplot2 here: ggplot colors.

manual fill values mosaic plot

1
On

If you want to color by the y axis categories you have to map this variable on fill, i.e. do fill = y:

library(ggplot2)
library(ggmosaic)

ggplot(bd) +
  geom_mosaic(aes(
    x = product(y, z),
    fill = y, weight = weight
  ), offset = 0.015) +
  scale_fill_brewer(palette = 2) +
  theme_mosaic()

enter image description here