Closed as not planned
Closed as not planned
Description
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:
- Is the reverse label order intended, when calling
fill
in theaes
ofgeom_bar
(and without adding the fill variable togroup
ingeom_text
)? Why is the default labeling in reverse order? - Might the warning when providing
fill
toaes
ingeom_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))