Skip to content

Ordering of label placement with geom_text() depends on whether or not a group aesthetic is set #3612

Closed as not planned
@TimTeaFan

Description

@TimTeaFan

When creating a stacked bar chart and the fill argument is not placed in the initial ggplot call, but in the aes of geom_bar, the label order of geom_text is displayed in reverse order. This behavior can be prevented, when adding fill to the aes of geom_text, however, this produces a warning saying ...

Ignoring unknown aesthetics: fill

... which is not really correct, since this unknown aesthetics still has some effect on the final plot.

I posted this on SO and Claus Wilke found out that the issue is related to grouping. Once the fill variable is added to geom_text(... group = ...) labels are displayed in correct order.

I see two possible issues here:

  1. Is the reverse label order intended, when calling fill in the aes of geom_bar (and without adding the fill variable to group in geom_text)? Why is the default labeling in reverse order?
  2. Might the warning when providing fill to aes in geom_bar be misleading, since it still has an effect on the plot?

A short example:

library(dplyr)
library(ggplot2)

# some toy data
data <- tibble(Category = c("Baseball",
                            "Basketball",
                            "Football",
                            "Hockey"),
               n = c(45,10,25,20)) 

  # fill is provided to the initial ggplot call - labels are in correct order
  ggplot(data, aes (x="", y = n, fill = Category)) +
    geom_bar(width = 1, stat = "identity") +
    geom_text(aes(label = paste(n, "%")),
            position = position_stack(vjust = 0.5))

   # fill is provided to geom_bar - labels are in reverse order
  ggplot(data, aes (x="", y = n)) +
    geom_bar(aes(fill = Category), width = 1, stat = "identity") +
    geom_text(aes(label = paste(n, "%")),
              position = position_stack(vjust = 0.5))

  # fill is provided to aes in geom_text - yields warning, but labels are in correct order
  ggplot(data, aes (x="", y = n)) +
  geom_bar(aes(fill = Category), width = 1, stat = "identity") +
  geom_text(aes(fill = Category, label = paste(n, "%")),
          position = position_stack(vjust = 0.5))
  #> Warning: Ignoring unknown aesthetics: fill

  # fill variable is provided to group in geom_text - labels are in correct order
  ggplot(data, aes (x="", y = n)) +
    geom_bar(aes(fill = Category), width = 1, stat = "identity") +
    geom_text(aes(label = paste(n, "%"), group = Category),
              position = position_stack(vjust = 0.5))

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions