Jennifer Matthews
Jennifer Matthews

Reputation: 15

Make the bars in a stacked bar plot different colours ggplot

How can I make the bars (representing treatments "B1" and "D1a") different colours. They are both red right now, how do I make B1 red (stacked bold red under pale red) and D1a blue (stacked bold blue under pale blue) for example?
Here is my script so far:

#glucose
x<-data.frame(
  Period = c("B1","D1a"),
  Sample = c("Glucose","Glucose"),
  Mi = c(34.01497478, 7.616569764),
  M0 = c(116.6844713,11.88958888)
)

mx <- melt(x,  id.vars=1:2)

mx <- mx %>% group_by(Period) %>%
  mutate(pos = cumsum(value)) %>%
  ungroup() %>%
  mutate(ci = c(1.773332238, 1.0661239, 6.083212937, 1.664236691),
         upper = pos + ci/2,
         lower = pos - ci/2)

b<-ggplot(mx, aes(x=Period, y=value, fill=variable), xLabels=NA) +
  geom_bar(stat="identity", width=0.65, aes(alpha=variable)) +       
  scale_alpha_manual(values=c(0.9,0.35)) +
  geom_errorbar(aes(ymin = lower, ymax = upper), width = .3,size = 0.6, col = "black") +
  facet_grid(~Sample) +
  scale_fill_manual(values = c("red","red")) +
  theme_bw() +
  xlab("") + 
  ylab("")

b+theme(axis.text=element_text(size=20),
        axis.title=element_text(size=22,face="bold"),
        text = element_text(size=45),
        legend.position="none")

Many thanks.

Upvotes: 0

Views: 3304

Answers (1)

Haboryme
Haboryme

Reputation: 4761

You can do:

b<-ggplot(mx, aes(x=Period, y=value ,fill=Period), xLabels=NA) +
  geom_bar(stat="identity", width=0.65, aes(alpha=variable)) +       
  scale_alpha_manual(values=c(0.9,0.35)) +
  geom_errorbar(aes(ymin = lower, ymax = upper), width = .3,size = 0.6, col = "black") +
  facet_grid(~Sample) +
  # scale_fill_manual(values = c("red","red")) +
  scale_fill_manual(values=c("red","blue"))+
  theme_bw() +
  xlab("") + 
  ylab("")

b+theme(axis.text=element_text(size=20),
        axis.title=element_text(size=22,face="bold"),
        text = element_text(size=45),
        legend.position="none")

Which gives:

enter image description here

/!\ Note that if you display the legend you will have 2 entries, one for the colours and one for the alphas.

Upvotes: 2

Related Questions