首页 文章

在堆积条形图中使用多个色标与ggplot

提问于
浏览
0

我有一个数据集,其中单个样本属于一个大组和一个较小的子组 . 每个组有几个子组,但每个子组只能属于一个更大的组 . 同样,每个样本只能属于一个子组,因此只能属于一个较大的组 .

我想制作一个有两种颜色含义的真/假堆叠条形图:

  • 轮廓(颜色)是较大的组

  • Fill是True / False数据,但是较大的组轮廓颜色的两种阴影 .

这与我想要的很接近,但不是浅灰色和深灰色,我想要红色水果的浅红色和深红色,绿色水果的浅绿色和深绿色,蓝色水果的浅蓝色和深蓝色 .

fruit <- data.frame(Sample=1:20, 
                Fruit=c(rep("Apple", 3), rep("Strawberry", 2), rep("Grape", 4), 
                      rep("Watermelon", 4), rep("Lime", 3), rep("Blueberry", 2), 
                      rep("Plum", 2)), 
                Color=c(rep("Red", 9), rep("Green", 7), 
                        rep("Blue", 4)), 
                Ripe=c(rep(c(T, F), 10)))

fruit$Fruit <- factor(fruit$Fruit, unique(fruit$Fruit))
fruit$Color <- factor(fruit$Color, unique(fruit$Color))

ggplot(fruit, aes(Fruit)) +
    theme_bw() +
    geom_bar(stat="count", position="fill",
             aes(fill=Ripe, color=Color)) +
    scale_fill_manual(values=c("grey65", "grey85")) +
    scale_y_continuous(labels=scales::percent)

example

这可能吗?或者,有没有更好的方法可以直观地将较大的组成员资格与真/假值区分开来?谢谢

1 回答

  • 3

    Edit: 这可能是更正确的方法,使用 interaction 为每个因子对分配唯一的颜色:

    ggplot(fruit, aes(Fruit)) +
      geom_bar( aes(fill=interaction(Color,Ripe), color=Color), stat="count", position="fill")+ 
      scale_y_continuous(labels=scales::percent)+
      scale_fill_manual(values=c("pink","lightgreen","lightblue","red", "green","blue"))+
      theme_bw()
    

    enter image description here

    将颜色映射到 fill ,将成熟映射到 alpha

    ggplot(fruit, aes(Fruit)) +
      geom_bar(stat="count", position="fill",
                 aes(fill=Color, color=Color,alpha=Ripe)) + 
      scale_y_continuous(labels=scales::percent)+
      scale_alpha_discrete(range=c(.5,1))+
      theme_bw()
    

    enter image description here

相关问题