使堆积条形图条形成不同颜色的ggplot

时间:2016-11-09 09:15:26

标签: r ggplot2 colors stacked

如何使条形(代表处理“B1”和“D1a”)具有不同的颜色。它们现在都是红色的,我如何制作B1红色(在浅红色下叠加大胆的红色)和D1a蓝色(在浅蓝色下叠加大胆的蓝色)? 到目前为止,这是我的脚本:

#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")

非常感谢。

1 个答案:

答案 0 :(得分:2)

你可以这样做:

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")

给出了:

enter image description here

/!\ 请注意,如果您显示图例,则会有2个条目,一个用于颜色,另一个用于alpha。