How to customise the colors in stacked bar charts

Viewed 36

Maybe a question someone already asked.

I have a data frame (dat) that looks like this:

    Sample      perc       cl  
      a          30         0
      b          22         0
      s          2          0
      z          19         0
      a          12         1
      b          45         1
      s          70         1
      z          1          1
      a          60         2
      b          67         2
      s          50         2
      z          18         2 

I would like to generate a stacked barplot. To do this I used the following:

g = ggplot(dat, aes(x = cl, y = Perc,fill = Sample)
    g + geom_bar(stat="identity", position = "fill", show.legend = FALSE) +
    scale_fill_manual(name = "Samples", values=c("a"="blue","b" = "blue","s" = "gray","z" = "red"))`

Fortunately the colors are assigned correctly. My point is that the order of samples in the bar is from a to z from the top to the bottom of the bar but I would like a situation in which the gray is on the top without loss of continuity in the bar from the blue to the red. Maybe there's another way to color the bars and set the desired order.

1 Answers

The groups are plotted in the bars in the order of the factor levels. You can change the plotting order by changing the order of the factor levels in your call to aes with factor(var, levels(var[order])) like this:

library(ggplot2)
ggplot(dat, aes(x = cl, y = perc,
                fill = factor(Sample, levels(Sample)[c(3,1,2,4)]))) +
  geom_bar(stat="identity", position = "fill", show.legend = FALSE) +
  scale_fill_manual(name = "Samples",
                    values=c("a"="blue","b" = "blue","s" = "gray","z" = "red"))

enter image description here

Related