Using multiple color scales in stacked bar plots with ggplot

I have a dataset where individual samples belong to a large group and a smaller subgroup. Each group has several subgroups, but each subgroup can only belong to one larger group. Likewise, each sample can only belong to one subgroup, and thus one larger group.

I want to make a True/False stacked bar plot with two color meanings:

  • Outline (color) is the larger group
  • Fill is the True/False data, but is two shades of the larger group outline color.
  • This is close to what I want, but instead of light and dark grey, I would like light and dark red for the red fruits, light and dark green for the green fruits, and light and dark blue for the blue fruits.

    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)
    

    例

    Is this possible? Or is there a better way I can visually distinguish the larger group membership with the true/false values? Thanks


    Edit: this is probably the more correct way to do it, using interaction to assign unique colors for each factor pair:

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

    在这里输入图像描述

    Map Color to fill , and Ripe to 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()
    

    在这里输入图像描述

    链接地址: http://www.djcxy.com/p/30966.html

    上一篇: 用于阅读CSV部分的翻转方法

    下一篇: 使用ggplot在堆积条形图中使用多个色标