barplot with ggplot2 and fct_reorder: how to sort bars when values are equal?

As you can see here, column A was plotted before Total because their values were the same. I think the reason was the bars were sorted by alphabetical order. How can I make sure that column Total will always be the 1st column? Thank you

library(ggplot2)
#> Warning: package 'ggplot2' was built under R version 4.2.2
library(forcats)
#> Warning: package 'forcats' was built under R version 4.2.2

data <- data.frame(x = c("A", "B", "C", "Total"), 
                   y = c(3, 0, 0, 3))
data
#>       x y
#> 1     A 3
#> 2     B 0
#> 3     C 0
#> 4 Total 3

ggplot(data, 
       aes(fct_reorder(x, -y), y)) +
  geom_col() +
  theme_classic()

Created on 2023-02-06 with reprex v2.0.2

There must be an easier way of doing this but I think this works

dat1<- data.frame(x = c("A", "B", "C", "Total"), 
                   y = c(3, 0, 0, 3))

dat1$x <-  factor(dat1$x, levels = c("Total","A", "B", "C"), ordered = TRUE)

ggplot(dat1, aes(x, y)) +
  geom_col() +   theme_classic()

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.