0

I have the below bar chart where I am plotting various shopping categories and the percentages. I would like to order them in descending order, can you please advise?

S2<- ggplot(data = data) + 
  geom_bar(mapping = aes(x = category), ..prop.., group = 1), stat = "count") + 
  scale_y_continuous(labels = scales::percent_format()) + 
  coord_flip()+ ylab("Total transactions %") + labs(title="Total Transactions by Category")+
  theme_classic()
S2

enter image description here

However if I try to use fct_reorder() in the code below it breaks:

data %>%
  count(category) %>%
  mutate(category = fct_reorder(category, n, .desc = TRUE)) %>%
  ggplot(aes(x = category, y = n)) + geom_bar(stat = 'identity')+ 
  geom_bar(mapping = aes(x = category), ..prop.., group = 1), stat = "count")+
  coord_flip()+ ylab("Total transactions %") + labs(title="Total Transactions by Category")+
  theme_classic()
SidStack
  • 59
  • 1
  • 9
  • Hi SidStack. This is a question that has been asked many times before on Stack Overflow. I have therefore closed this as a duplicate. If you go to the linked duplicate question there are some excellent answers and you should get what you're looking for there. If for some reason you can't get any of them to work, please edit your question to include reproducible data and show at what point you got stuck. Good luck! – Allan Cameron Dec 01 '20 at 13:38
  • I went through those threads and I still can;t fix the code. – SidStack Dec 01 '20 at 13:47
  • if you can edit your post to include your data, then I can reopen it so we can have a look. Without your data, there's no way to see whether there may be something wrong with the structure of your data frame, or to test possible solutions. Having said that, you could try just deleting the line `geom_bar(mapping = aes(x = category), ..prop.., group = 1), stat = "count")+` which is unnecessary since you already have a `geom_bar` call in the line above, and it is syntactically incorrect (there is an extra bracket after `x = category` that shouldn't be there.) – Allan Cameron Dec 01 '20 at 13:53
  • I want to use % and not count, thats why I used that line. Do you have any other recommendation where i can get a % and then still reorder? – SidStack Dec 02 '20 at 03:39
  • add the line `+ scale_y_continuous(labels = scales::percent)` – Allan Cameron Dec 02 '20 at 07:14

0 Answers0