0

I have a stacked barplot with the following data

df <- expand.grid(name = c("oak","birch","cedar"),
    sample = c("one","two"),
    type = c("sapling","adult","dead"))
df$count <- sample(5:200, size = nrow(df), replace = T)

I generate a barplot and try to add the group lables to it:

ggplot(df, aes(x = name, y = count, fill = type)) +
   geom_bar(stat = "identity") +
   coord_flip() +
   theme(legend.position="none") +
   geom_text(aes(label = type, position = "stack")) 

It produces: Barplot with ugly labels

Two to three questions arise:

  1. How can I make the labels appear in the top bar only?

  2. How can I make the labels appear in the center of the bar section?

  3. Optionally: How can I make the labels appear on top of the top bar being connected to their sections by arrows?

MERose
  • 4,048
  • 7
  • 53
  • 79
  • http://stackoverflow.com/questions/6644997/showing-data-values-on-stacked-bar-chart-in-ggplot2 should help you for the positioning; for labeling only selected values I would introduce a new variable label which takes the value of type for cedar and is empty for the other trees – CMichael Nov 15 '14 at 22:15

1 Answers1

2

There is a link suggested above. That will help you. Here, I have another suggestion.

set.seed(123)
df <- expand.grid(name = c("oak","birch","cedar"),
                  sample = c("one","two"),
                  type = c("sapling","adult","dead"))
df$count <- sample(5:200, size = nrow(df), replace = T)

### Arrange a data frame (summing up sample one and two)
library(dplyr)
ana <- df %>%
        group_by(name, type) %>%
        summarise(total = sum(count))

# Draw a figure once        
bob <- ggplot(ana, aes(x = name, y = total, fill = type)) +
       geom_bar(stat = "identity", position = "stack")

# Get a data frame for ggplot      
cathy <- ggplot_build(bob)$data[[1]]

# calculate text position & add text labels
cathy$y_pos <- (cathy$ymin + cathy$ymax) / 2
cathy$label <- rep(c("sampling", "adult", "dead"), times = 3)

# Subset the data for labeling for the top bar
dan <- cathy[c(7:9), ]

# Draw a figure again
bob + 
annotate(x = dan$x, y = dan$y_pos, label = dan$label, geom="text", size=3) +
coord_flip()

enter image description here

jazzurro
  • 23,179
  • 35
  • 66
  • 76
  • I presume, it's not possible to put the labels above the top bar and combine them to their bar sections by arrows? MS Excel somehow can (although not necessarily for stacked bars). – MERose Nov 16 '14 at 15:04
  • @MERose You can move a legend to the top position. But I do not think `ggplot` has the arrow thing. – jazzurro Nov 16 '14 at 15:06