1
votes

I have the following data set

example <- structure(list(selection_type = c("P", "G"), count = c(44L, 
102L), var = c("ST", "ST")), row.names = c(NA, 
-2L), class = c("tbl_df", "tbl", "data.frame"))

I produce the following plot:

ggplot(example) +
  geom_bar( aes(x = var, y = count, fill = selection_type), stat = "identity") +
  coord_flip()

enter image description here


Problem: I need it backwards. So "P" at the "right" of the stacked bar.

I have tried:

  • Arrange on the dataframe and then plot, it doesn't work
  • x = reorder(var,count) and x = reorder(var,-count) also doesn't work
1

1 Answers

1
votes

You could use fct_rev from the forcats package

library(tidyverse)
example <- structure(list(selection_type = c("P", "G"), count = c(44L, 
                                                                  102L), var = c("ST", "ST")), row.names = c(NA, 
                                                                                                             -2L), class = c("tbl_df", "tbl", "data.frame"))

ggplot(example) +
  geom_bar( aes(x = var, y = count, fill = fct_rev(selection_type)), stat = "identity") +
  coord_flip()

enter image description here