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

Using multiple color scales in stacked bar plots with ggplot

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

我想制作一个 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)

这可能吗?或者有没有更好的方法可以直观地区分具有 true/false 值的较大组成员? 谢谢

编辑: 这可能是更正确的方法,使用 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()

将颜色映射到 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()