【问题标题】:Using multiple color scales in stacked bar plots with ggplot使用 ggplot 在堆积条形图中使用多个色标
【发布时间】:2017-10-04 21:55:24
【问题描述】:

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

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

  • 轮廓(颜色)是较大的组
  • Fill 是真/假数据,但 是较大组轮廓颜色的两种色调。

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

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)

这可能吗?或者有没有更好的方法可以用真/假值在视觉上区分较大的组成员? 谢谢

【问题讨论】:

标签: r ggplot2 colors geom-bar stackedbarseries


【解决方案1】:

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

【讨论】:

  • 谢谢!我更喜欢使用 alpha 的外观。
  • 在第二个示例中,如果我希望 y 轴是水果的“计数”而不是百分比怎么办?此外,成熟的“计数”......
  • @guidebortoli 我会先使用dplyr 聚合:fruit2 &lt;- fruit %&gt;% group_by(Fruit, Ripe) %&gt;% summarize(count = n(), Color = first(Color)) 然后ggplot(fruit2, aes(Fruit,count))+ geom_bar(stat="identity",aes(fill=interaction(Color,Ripe), color=Color))+scale_fill_manual(values=c("pink","lightgreen","lightblue","red", "green","blue"))+ theme_bw()
  • 完美运行!!我想知道您是否知道如何将 TRUE 的观察总数 n 放在每个颜色条中。在这种情况下,每个条形将有两个 n 观察值,条形上方的一个作为每种颜色的总 n,而 TRUE 条形上方是该特定颜色的 TRUE n 观察值...
  • @guidebortoli 如果您找不到答案,请提出一个新问题。这样其他人也可以找到它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-22
  • 1970-01-01
  • 2014-11-22
相关资源
最近更新 更多