Search code examples
rggplot2stacked-bar-chart

Changing color of only one stacked bar using ggplot


I have a stacked bar chart made with ggplot in R (markdown). I want the stacked bar for "north" to be in a grayscale, and the other bars to stay in the color scale they currently are. I am in reality working with a lot larger data set, so the solution should preferably find where x = "north" and grayscale only that bar.

Region <- c("north", "south", "east", "west", "north", "south", "east", "west")
q14 <- c("5", "5", "5", "5", "4", "4", "4", "4")
N <- c(4342, 5325, 654, 1231, 3453, 234, 345, 5634)
Percentage <- c(72, 71, 68, 67, 21, 20, 18, 17)
df <- data.frame(Region, q14, N, Percentage)

ggplot(df, aes(x=Region, y = Percentage, fill = q14, label = Percentage)) + 
  geom_bar(stat = "identity") +
  scale_fill_manual(values = c("#bbd6ad", "#63ab41"))

Super thankful for help!

I have tried tweaking scale_fill_manual without any good result, only resulting in changing the color of all bars.


Solution

  • Possibly the following

    Region <- c("north", "south", "east", "west", "north", "south", "east", "west")
    q14 <- c("5", "5", "5", "5", "4", "4", "4", "4")
    N <- c(4342, 5325, 654, 1231, 3453, 234, 345, 5634)
    Percentage <- c(72, 71, 68, 67, 21, 20, 18, 17)
    df <- data.frame(Region, q14, N, Percentage)
    
    df <- mutate(df,
      q14 = case_when(
        Region == "north" &
          q14 == 4 ~ "4 North",
        Region == "north" ~ "5 North",
        q14 == 4 ~ "4",
        TRUE ~ "5"
      )
    )
    
    
    ggplot(df, aes(
      x = Region, y = Percentage,
      fill = q14,
      label = Percentage
    )) +
      geom_bar(stat = "identity") +
      scale_fill_manual(
        values =
          c(
            "4 North" = "#444444",
            "5 North" = "#AAAAAA",
            "4" = "#63ab41",
            "5" = "#bbd6ad"
          )
      )