rggplot2fontsggfittext

ggfittext::geom_bar_text does not place text in centre when fontface = "bold" is involved, also values are mixed up


I want to use ggfittext::geom_bar_text() to plot values into a horizontal stacked bar plot with a certain value in bold font. There is a fontface aesthetic available. The problem is: As soon as I use a bold fontface, the labels are not centered anymore and the values get mixed up.

Please have a look at this MRE:

library(ggplot2)
library(ggfittext)
library(scales)

This is the case without any bold labels:

df2 <- data.frame(cat1 = rep(c("A", "B", "C"), each = 3),
                 cat2 = rep(c("D", "E", "F"), 3),
                 perc = c(0, .6, .4,
                          .26, .24, .5,
                          .3, .3, .4),
                 fface = "plain")

ggplot(df2, aes(y = cat1, fill = cat2, x = perc, fontface = fface)) +
  geom_col() +
  geom_bar_text(aes(label = percent(perc, accuracy = .1),
                    fontface = fface),
                position = "stack", place = "centre")

correct plot

Now for the problematic case:

df <- data.frame(cat1 = rep(c("A", "B", "C"), each = 3),
                 cat2 = rep(c("D", "E", "F"), 3),
                 perc = c(0, .6, .4,
                          .26, .24, .5,
                          .3, .3, .4),
                 fface = c("plain", "bold", "plain",
                           "bold", "plain", "plain",
                           "plain", "plain", "bold"))

ggplot(df, aes(y = cat1, fill = cat2, x = perc, fontface = fface)) +
  geom_col() +
  geom_bar_text(aes(label = percent(perc, accuracy = .1),
                    fontface = fface),
                position = "stack", place = "centre")

incorrect plot

What is happening? df is exactly identical except for the three bold cases in column fface and the ggplot() calls are also exactly identical. But the labels for cat1 == "C" are off and they are switched, too.

Am I missing something? Is this a bug? Thank you for your help!


Solution

  • That's simply a matter of the default groupìng which in your case also takes the fontface into account. To fix you issue map explicitly on the group= aes to group and stack by the fill variable only:

    library(ggplot2)
    library(ggfittext)
    library(scales)
    
    ggplot(df, aes(y = cat1, fill = cat2, x = perc)) +
      geom_col() +
      geom_bar_text(
        aes(
          label = percent(perc, accuracy = .1),
          fontface = fface,
          group = cat2
        ),
        position = "stack", place = "centre"
      )