1
votes

I would like to make a stacked histogram in ggplot, where each of the bars (and stacked bars) have a unique colour - using a provided hex value.

For example, take this dataframe.

Pct <- c(0.8026200, 0.1973800, 0.8316421, 0.1683579)
Site <- c("A","A","B", "B")
hex <- c("#53412F", "#B4A383", "#4E3B29", "#B6A37E")
bin <- rep(c(1,2), 2)

df <- as.data.frame(cbind(Site,Pct,hex,bin))

I would like to use the hex colours specified to colour the corresponding bars.

I have tried variations along these lines:

ggplot()+
  geom_bar(aes(y=Pct, x=as.character(Site), fill=bin), data=df, stat="identity")+
  theme_bw() +
  scale_fill_manual("Subject", values=df$hex)

but this produces a green and red colour for each plot?

Any help would be greatly appreciated. Sorry if it is a simple solution - I have not got much experience with stacked barcharts.

Thank you in advance!

1

1 Answers

2
votes

your issue comes from a little contradiction I think : you say to ggplot to attribute the aesthetic "fill" using the variable "bin". Since "bin" only have two possibility ("1" or "2"), ggplot uses only 2 colors. It uses the two firsts, which are green and red.

I am not sure what you exactly want, but if you want a distinct color for each bar, then you have either to change "bin" like in the example below, or to give another argument to "fill", for example you can just replace "fill = bin" by "fill = hex". But if you want 4 colors, then the variable used in "fill" has to have 4 different values (below, I choosed "bin", and the values are 1,2,3,4).

Example :

Pct <- c(0.8026200, 0.1973800, 0.8316421, 0.1683579)
Site <- c("A","A","B", "B")
hex <- c("#53412F", "#B4A383", "#4E3B29", "#B6A37E")

##bin is defined in order it has a different value for each bar
bin <- c(1,2,3,4)
df <- as.data.frame(cbind(Site,Pct,hex,bin))

ggplot()+
  geom_bar(aes(y=Pct, x=as.character(Site), fill=bin)
           , data=df, stat="identity")+
  theme_bw() +
  scale_fill_manual(values=hex)

Result:

enter image description here

Hope it will clarify your problem!