使用堆叠条形图中的多个色标将y轴刻度更改为计数

时间:2018-01-27 14:05:37

标签: r ggplot2 bar-chart geom-bar stackedbarseries

我的df如下:

fruit <- data.frame(Sample=1:100, 
            Fruit=c(rep("Apple", 10), rep("Strawberry", 25), rep("Grape", 20), 
                  rep("Watermelon", 15), rep("Lime", 11), rep("Blueberry", 10), 
                  rep("Plum", 9)), 
            Color=c(rep("Red", 30), rep("Green", 45), 
                    rep("Blue", 25)), 
            Ripe=c(rep(c(T, F), 50)))+
fruit$Fruit <- factor(fruit$Fruit, unique(fruit$Fruit))+
fruit$Color <- factor(fruit$Color, unique(fruit$Color))

然后,我将条形图绘制为:

library(ggplot2)
ggplot(fruit, aes(Color)) +
geom_bar(stat="count", position="fill",aes(fill=Color, color=Color,alpha=Ripe)) +
scale_y_continuous(labels=scales::percent)+
scale_alpha_discrete(range=c(1,0.6))+
theme(axis.title.x = element_blank(), axis.text.x = element_blank(), axis.ticks.x = element_blank())+
scale_color_manual(values = c("Black", "Black", "Black"))+
guides(fill = guide_legend(override.aes = list(colour = NA)))

结果是:

enter image description here

想要得到的是y轴刻度作为从Color变量观察的计数而不是频率(百分比)。

根据@PoGibas给出的答案,我能够将每种颜色的观察总数放在每个柱子上方......但我想知道你是否知道如何将观察总数n设为TRUE在每个颜色栏中。在这种情况下,对于每个条形将是两个n观察,其中一个在条形图上方作为每个颜色的总n并且在TRUE条形图上方对于该特定颜色的TRUE n观察...

2 个答案:

答案 0 :(得分:4)

您的ggplot2代码有些过于复杂。您必须删除scale_y_continuous(labels = scales::percent)才能摆脱百分比。并移除stat = "count"position = "fill"以获取观察计数(即使用简单的geom_bar())。

# Using OPs data
library(ggplot2)
ggplot(fruit, aes(Color, fill = Color, alpha = Ripe)) +
    geom_bar(color = "black") +
    scale_alpha_discrete(range = c(1, 0.6)) +
    theme(axis.title.x = element_blank(), 
          axis.text.x = element_blank(), 
          axis.ticks.x = element_blank()) +
    guides(fill = guide_legend(override.aes = list(colour = NA)))

enter image description here

此外,您指定color = Color,然后使用scale_color_manual(values = c("Black", "Black", "Black"))

覆盖它

答案 1 :(得分:1)

你也可以使用stat_count

ggplot(fruit,aes(Color)) +
    stat_count(aes(x=Color,fill=Color, color=Color,alpha=Ripe),geom = "bar",position = "stack")+
    scale_y_continuous()+scale_alpha_discrete(range=c(1,0.6))+
    theme(axis.title.x = element_blank(), axis.text.x = element_blank(), axis.ticks.x = element_blank())+
    scale_color_manual(values = c("Black", "Black", "Black"))+
    guides(fill = guide_legend(override.aes = list(colour = NA)))

enter image description here