rggplot2stackedbarseries

Character labels on top of R ggplot stacked bar have transparent background, instead of white background


I'm trying to show relative frequencies of phonemes from an specific corpus using R and ggplot stacked bars. I'm not able to show labels of each phoneme on top of the bars with a white background and black line. Labels appear with a transparent background!

enter image description here

This is the data.frame I am using:

phones  <- c("i", "e", "ə", "a", "o", "u", "p", "t̪", "t", "t͡ʃ", "ʈ͡ʂ", "k", "m", "n̪", "n", "ɲ", "ŋ", "f", "θ", "s", "ʃ", "ɻ", "j", "ɣ", "w", "l̪", "l", "ʎ")
mode    <- c(rep("vowel", 6), rep("stop", 3), rep("affricate", 2), "stop", rep("nasal", 5), rep("fricative", 4), rep("approximant", 4), rep("lateral", 3))
freq    <- c(3629, 6301, 8967, 7204, 2403, 5120, 2798, 74, 2095, 1359, 1767, 5233, 3059, 353, 9769, 1439, 2061, 1994, 1338, 97, 353, 1652, 1597, 361, 3435, 409, 3731, 1378)
data <- data.frame(phones, mode, freq)

An this is the code I am using to generate the graph.

library(ggplot2) #for ggplot
ggplot(data, aes(fill = reorder(phones, freq), y = freq, x = mode, label = phones)) + 
  geom_bar(position = "fill", stat = "identity", colour = "white") +
  xlab("") +
  ylab("") +
  labs(title = "Frecuencia de fonemas del diccionario Augusta", fill = "Phones", caption  = "Elaboración propia" ) +
  scale_y_continuous(breaks = seq(0, 1, 0.25), labels = function(x){paste0(x * 100,  "%") } ) +
  coord_flip() +
  geom_label(position = position_fill(vjust = 0.5), colour="black", size = 2) +
  theme(legend.position="None") + 
  labs(subtitle="")

I appreciate any help in order to display the labels correctly (white background + black text and lines).


Solution

  • Actually, it turns out that the backgrounds of your labels aren't transparent; they're the same color as the bars. (We can see this in the label of [t̪], which extends beyond the bounds of its bar.) This is because geom_label is inheriting the fill aesthetic.

    We can force the labels' fill to be a different color by specifying fill = "white". If we do this, we also have to explicitly specify the group aesthetic so that position_fill() will put the labels in the correct locations.

    ggplot(data, aes(fill = reorder(phones, freq), group = reorder(phones, freq),
                     y = freq, x = mode, label = phones)) +
      geom_bar(position = "fill", stat = "identity", colour = "white") +
      xlab("") +
      ylab("") +
      labs(title = "Frecuencia de fonemas del diccionario Augusta", fill = "Phones", caption  = "Elaboración propia" ) +
      scale_y_continuous(breaks = seq(0, 1, 0.25), labels = function(x){paste0(x * 100,  "%") } ) +
      coord_flip() +
      geom_label(position = position_fill(vjust = 0.5), fill = "white", colour="black", size = 2) +
      theme(legend.position="None") +
      labs(subtitle="")
    

    enter image description here