guidebortoli
guidebortoli

Reputation: 679

ggplot2: label n observations for alpha on stacked bars

I have a df as it follows:

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

Then, I've plotted the bar graph:

foo <- aggregate(Sample ~ Color, data = fruit, FUN = length)

library(ggplot2)
ggplot(fruit, aes(Color, fill = Color, alpha = Ripe)) +
geom_bar(color = "black") +
geom_text(data = foo, aes(label = Sample, y = Sample), alpha = "1", vjust = -1)
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)))

With the command above I was able to create the following bar-graph:

enter image description here

So...I was able to put the total number of observations for each Color above each bar...but I don't this....rather, I'm wonder how can I put the total n of observation for TRUE in each color bar instead. In this case it would be one n observation for each bar, with one above the above the TRUE bar for the TRUE n observation for that particular Color...

Upvotes: 0

Views: 692

Answers (1)

GL_Li
GL_Li

Reputation: 1798

You can use calculating power of stat in ggplot2

enter image description here

ggplot(fruit, aes(Color, fill = Color, alpha = Ripe)) +
    geom_bar() +
    geom_text(stat = "count", aes(y = ..count.., label = ..count..), 
              position = "stack", show.legend = FALSE) +
    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))) 

Upvotes: 1

Related Questions