【问题标题】:Make the bars in a stacked bar plot different colours ggplot使堆积条形图中的条形图具有不同的颜色ggplot
【发布时间】:2016-11-09 09:15:25
【问题描述】:

我怎样才能使条(代表处理“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")

非常感谢。

【问题讨论】:

    标签: r ggplot2 colors stacked


    【解决方案1】:

    你可以这样做:

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

    这给出了:

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

    【讨论】:

    • 您的代码为我生成了正确的图(在 ggplot2 的开发版上),但此处显示的图显然颠倒了堆叠条(因此错误条位于错误的位置)。跨度>
    • 我没有更改太多代码,但是是的,我想我应该已经看到了。 Ty 指出来。
    • 非常感谢!感谢您指出错误栏。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-02
    • 1970-01-01
    • 1970-01-01
    • 2017-03-31
    相关资源
    最近更新 更多