3

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?

Thirst for Knowledge
  • 1,606
  • 2
  • 26
  • 43

3 Answers3

6

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

user126082
  • 310
  • 2
  • 9
0

Something like this? The position stack.

g <- ggplot(df, aes(x = geotype, y = capacity, fill = metric, label = 
capacity))
g + geom_col() + facet_grid(~limitations) +
geom_text(size = 3, vjust =3, position = position_stack())
william3031
  • 1,653
  • 1
  • 18
  • 39
0

You can set the labels in the mail ggplot aes

ggplot(df, aes(x = geotype, y = capacity, fill = metric, label = capacity ) ) + 
  geom_col() + 
  geom_text( size = 3, position = position_stack( vjust = 0.5 ) ) +
  facet_grid( ~limitations )

enter image description here

Wimpel
  • 26,031
  • 1
  • 20
  • 37