Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2 putting data labels (geom_text) in wrong order

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:

enter image description here

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?

like image 965
Thirst for Knowledge Avatar asked Apr 09 '26 20:04

Thirst for Knowledge


1 Answers

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)

enter image description here

like image 200
user126082 Avatar answered Apr 12 '26 15:04

user126082



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!