I'm having an issue with data labels incorrectly ordering using ggplot2.
Unfortunately, other SE Q&As on this topic are not very insightful(example), so I'm having to reach out with a reprex. I have the following data:
df = as.data.frame(structure(list(geotype = c('urban','urban','urban','urban','suburban','suburban','suburban','suburban'),
limitations = c('all','some','all','some','all','some','all','some'),
metric = c('lte','lte','5g','5g','lte','lte','5g','5g'),
capacity=c(12,11,5,4,14,10,5,3))))
If I then try to plot this data using this code:
ggplot(df, aes(x = geotype, y = capacity, fill=metric)) + geom_bar(stat="identity") +
facet_grid(~limitations) +
geom_text(data = df, aes(geotype, capacity + 2, label=capacity), size = 3)
I get this incorrect labelling order:
I've played with the ordering of the variables for ages (e.g. rev(capacity)) but I can't fix the issue. Can anyone provide a more comprehensive answer for the whole SE community as to how to deal with label ordering?
You need to call the position
argument in geom_text
to match the filled aesthetics data with geom_bar
and to let the function know the data is stacked.
ggplot(df, aes(x = geotype, y = capacity, fill=metric)) +
geom_bar(stat="identity") +
geom_text(data = df, aes(geotype, capacity, label=capacity), size = 3, vjust = 2,
position = position_stack()) +
facet_grid(~limitations)