1

How do I preserve the order of the "net" in ggplot2 as in dataset? Currently, it is plotting in alphabetical order. I need Non-LTE > LTE > Mixed > 5G from bottom to top order in the plot.

df1 <- data.frame(product = c("A","A","A","A","B","B","C","C","C","C","D","D", "D"), 
                  net =c("5G", "Mixed", "LTE", "Non-LTE", "Mixed", "LTE", "5G", "Mixed", "LTE", "Non-LTE", "5G", "Mixed", "LTE"),
                  value = c(33.74, 21.62, 24.44, 20.20, 4.70, 95.30, 41.82, 39.60, 13.98, 4.61, 0.20, 0.20, 99.60))

color <- c('5G' = '#778899',
  'Mixed' = '#3CB371',
  'LTE' = '#58595b',
  'Non-LTE' = '#9ACD32')  

library(ggplot2)

plot1 <- ggplot(df1, aes(y = value, x = product, fill = net, label = paste0(value,"%"))) + geom_col() + scale_fill_manual(values= color) + geom_text(size = 4, position = position_stack(vjust = 0.5), color = "white")

enter image description here

UseR10085
  • 7,120
  • 3
  • 24
  • 54
Bodhi Bose
  • 33
  • 6
  • 3
    Does this answer your question? [Change the order of stacked fill columns in ggplot2](https://stackoverflow.com/questions/47025828/change-the-order-of-stacked-fill-columns-in-ggplot2) – UseR10085 Jul 10 '20 at 07:15

1 Answers1

2

Use

color <- c('5G' = '#778899',
           'Mixed' = '#3CB371',
           'LTE' = '#58595b',
           'Non-LTE' = '#9ACD32')  

library(ggplot2)

df1$net <- factor(df1$net, levels = c("Non-LTE", "LTE", "Mixed", "5G"))

ggplot(df1, aes(y = value, x = product, fill = net, label = paste0(value,"%"))) +
  geom_col() + 
  scale_fill_manual(values= color) + 
  geom_text(size = 4, position = position_stack(vjust = 0.5), color = "white") +
  scale_y_reverse()

enter image description here

UseR10085
  • 7,120
  • 3
  • 24
  • 54