Thomas Eigentler
Thomas Eigentler

Reputation: 65

Set border in a stacked bar chart using ggplot2

I want to create a stacked bar chart and setting the border color to black for all 'D'-elements. Using

d <- ggplot(diamonds) +  geom_bar(aes(clarity, fill=color))    # first plot
d + geom_bar(data=diamonds[(diamonds$clarity=="SI2"),],        # filter
aes(clarity), alpha=0, size=1, color="black")

enter image description here

I'm able to highlight one column, but not one element in all columns. Any ideas how to set the border color just for the D's?

Upvotes: 5

Views: 6210

Answers (2)

arvi1000
arvi1000

Reputation: 9582

Sure, just map color, like this:

library(ggplot2)
ggplot(diamonds) +  
  geom_bar(aes(clarity, fill = color, 

               # 1) set the border (i.e. the color aesthetic) based on whether the value
               # of the relevant variable (which also happens to be called color) is D
               color = color=='D')) +

  # 2) use a scale such that FALSE is no color and TRUE is black, 
  # but don't include this in the legend
  scale_color_manual(values = c(NA, 'black'), guide=F)

enter image description here

Upvotes: 3

Jorge
Jorge

Reputation: 392

You can do this by using scale_color_manual() and assigning the color, in this case "D", black and all others NA:

library(ggplot2)
d <- ggplot(diamonds) +  geom_bar(aes(clarity, fill=color, colour = color)) +
  scale_color_manual(values = c("J" = NA,
                            "I" = NA,
                            "H" = NA,
                            "G" = NA,
                            "F" = NA,
                            "E" = NA,
                            "D" = "black"))

d

Upvotes: 2

Related Questions