Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Highlight one bar of a stacked bar chart in ggplot2

Tags:

r

ggplot2

I have a stacked bar chart and, inspired by Figure 3.8 on this page, I would like to highlight one bar of the bar chart. For example, I'd like all three colours for middle bar to be a notch darker and all the colours in the 1st and 3rd bars to be a little lighter. I'm assuming that the darken argument to scale_fill_OkabeIto could come in handy in some way.

library(ggplot)    
library(colorblindr)
ID <- rep(1:3, each = 3)
group <- rep(letters[1:3], times = 3)    
prop <- c(0.8, 0.1, 0.1, 0.6, 0.3, 0.1, 0.4, 0.3, 0.3)

toy_df <- data.frame(ID = ID, group = group, prop = prop)

ggplot(toy_df, aes(x = ID, y = prop, fill = group)) +
  geom_bar(stat = "identity") +
  scale_fill_OkabeIto()

Below is the graph so far:

I have seen posts showing how to do this for regular bar charts but can't figure out how to do this for a stacked bar chart.

Thanks for your help.

like image 678
EllaK Avatar asked Nov 21 '25 04:11

EllaK


2 Answers

The easiest way to do something like this is to change the alpha based on whether the ID is the one you want highlighted. You could make a boolean variable in your dataframe, something like isHilite = ID == 2, or you can just do it inline when you plot.

I dropped your color scale just because I don't have that package installed, and it wasn't necessary to show you this example.

Another option if you want to get into more complex color functions is the munsell package that works with a whole different color system. I haven't used it enough to put together a good answer with it, but it has functions for darkening, lightening, and desaturating color.

library(ggplot2)    
ID <- rep(1:3, each = 3)
group <- rep(letters[1:3], times = 3)    
prop <- c(0.8, 0.1, 0.1, 0.6, 0.3, 0.1, 0.4, 0.3, 0.3)

toy_df <- data.frame(ID = ID, group = group, prop = prop)

ggplot(toy_df, aes(x = ID, y = prop, fill = group)) +
    geom_bar(aes(alpha = ID == 2), stat = "identity") +
    scale_alpha_manual(values = c("TRUE" = 1, "FALSE" = 0.6), guide = F)

Created on 2018-04-23 by the reprex package (v0.2.0).

like image 200
camille Avatar answered Nov 22 '25 19:11

camille


Here is an easy way to do it, simply mapping alpha to whether the ID is a given value.

ggplot(toy_df, aes(x = ID, y = prop, fill = group, alpha=toy_df$ID != 2)) +
  geom_bar(stat = "identity") +
  scale_alpha_manual(values=c(1, 0.7)) +
  guides(alpha=F)

enter image description here

Of course, you can still use your colour-blind friendly colour set with this

like image 41
Luke Hayden Avatar answered Nov 22 '25 18:11

Luke Hayden



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!