1

I am trying to change color to specific variable in stacked bar chart in ggplot.

I've found this link, but it is not what I want. R ggplot Changing color of one variable in stacked bar graph

I want to change Brand7 color to black, but the rest of brands should be colored in different random colors.

What I want, is to use some kind of conditional to select color for one specific brand, the other brands could be as it was before.

Also I enclose reproducable example.

set.seed(1992)
n=8

Category <- sample(c("Car", "Bus", "Bike"), n, replace = TRUE, prob = NULL)
Brand <- sample("Brand", n, replace = TRUE, prob = NULL)
Brand <- paste0(Brand, sample(1:14, n, replace = TRUE, prob = NULL))
USD <- abs(rnorm(n))*100

df <- data.frame(Category, Brand, USD)



ggplot(df, aes(x=Category, y=USD, fill=Brand)) +
geom_bar(stat='identity')
Community
  • 1
  • 1
AK47
  • 1,318
  • 4
  • 17
  • 30

1 Answers1

3

You can use something like this, accessing the standard ggplot-colours and replacing the one you need.

Function to access ggplot-colors, source

gg_color_hue <- function(n) {
  hues = seq(15, 375, length=n+1)
  hcl(h=hues, l=65, c=100)[1:n]
}

#make custom palette

mycols <- gg_color_hue(length(unique(df$Brand)))
names(mycols) <- unique(df$Brand)
mycols["Brand7"] <- "black"

#use palette in scale_fill_manual

ggplot(df, aes(x=Category, y=USD, fill=Brand)) +
  geom_bar(stat='identity')+
  scale_fill_manual(values=mycols)

enter image description here

Community
  • 1
  • 1
Heroka
  • 12,889
  • 1
  • 28
  • 38