1

I'm dealing with a data-frame in R that looks like this

test <- data.frame(c(1:4),c(5:8),c(9:12),c(13:16))
names(test) <- c("position","totalA","totalB","totalC")

No I want to create a stacked barplot, where all bars are in black, except for 1 value of position, there I want different colors for 'totalA', 'totalB' and 'totalC'

This is what I did to create the barplot

test.melt <- melt(test, id = "position")
ggplot(test.melt, aes(x=position, y=value, fill=variable))+geom_bar(stat="identity")+scale_fill_manual(values=grey.colors(3))

enter image description here

so now all bars are conditionally colored, but this should only be the case when position == 2. For the rest all bars should be black.

EDIT: I need to do this also while just using the barplot() function instead of ggplot().

I use this for the barplot

test.transposed <- setNames(data.frame(t(test[,-1])), test [,1])
barplot(as.matrix(test.transposed))

But again, how can I now apply this conditional coloring ?

user1987607
  • 2,057
  • 6
  • 26
  • 53

2 Answers2

2

You can prepare the groups you need in the data like this:

test.melt$colour <- ifelse(test.melt$position == 2, 
                           as.character(test.melt$variable), "All other")
library(ggplot2)
ggplot(test.melt, aes(x=position, y=value, fill=colour))
  + geom_bar(stat="identity")
  + scale_fill_manual(values=c( "#000000", grey.colors(3)))

Which will produce:

Default colours to black

Bulat
  • 6,869
  • 1
  • 29
  • 52
0

You can specify the colors in scale_fill_manual: scale_fill_manual(values = c("#000000", "#dddddd", "#000000"))

ggplot(test.melt, aes(x=position, y=value, fill=variable))+geom_bar(stat="identity") + scale_fill_manual(values = c("#000000", "#dddddd", "#000000"))
kabr
  • 1,249
  • 1
  • 12
  • 22